The reason why the sendMessage() method is triggered twice when using @keyup.enter is because hitting the enter key triggers the form's default submit behavior in addition to the sendMessage() method. To prevent this, you can add event.preventDefault() to the sendMessage() method to stop the form from submitting twice. Here's an updated version of the code:
<template>
<form @submit.prevent="submit">
<div class="input-group">
<input
type="text"
class="form-control type_msg"
placeholder="Type your message..."
v-model="form.message"
@keyup.enter="sendMessage"
>
<input type="hidden" v-model="form.conversationID">
<button class="btn btn-success" @click="sendMessage" type="button">Send</button>
</div>
</form>
</template>
<script>
export default {
data() {
return {
form: useForm({
message: '',
conversationID: '',
fromID: '',
toID: '',
}),
}
},
methods: {
sendMessage(event) {
event.preventDefault()
console.log(this.form)
},
},
}
</script>
Note that we also changed the type="submit" attribute on the send button to type="button", since we're handling the form submission ourselves in the sendMessage() method.