Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  150] [ 2]  / answers: 1 / hits: 55094  / 7 Years ago, mon, december 18, 2017, 12:00:00

I have a text input that has a v-model and a v-on:change attached to it. As the user types I update an array in data and the UI is bound to that array. I also want to call a method to send the user input via AJAX. The data sent to the server is the result of a computed property.



<div id=app>
<input
id=user-input
type=text
v-model=userInput
v-on:change=process()>

<ul id=parsed-list>
<li v-for=item in parsedInput>
{{ item }}
</li>
</ul>
</div>

let parse = input => {
return input.split(',')
}

let serverProcess = values => {
// Send array to server
}

new Vue({
el: '#app',
data: {
userInput: ''
},
computed: {
parsedInput () {
return parse(this.userInput)
}
},
methods: {
process () {
serverProcess(this.parsedInput);
}
}
});


Is this usage of both a v-model and v-on:change together best practice Vue?


More From » vue.js

 Answers
16

I recommend using a watch instead of a v-on:change. In the view, you would remove the v-on:change. Any time parsedInput changes (due to userInput changing), then the watch function will be called. It is important that the watch function be named the same as the computed/data property.


new Vue({
computed: {
parsedInput () {
return parse(this.userInput)
}
}
methods: {
process () {
serverProcess(this.parsedInput);
}
},
watch: {
parsedInput() {
this.process()
}
}
})

You can read more about watches here https://v2.vuejs.org/v2/guide/computed.html#Watchers


IMO, this is better because you are describing more of the behavior of the application through code rather than the view. This would make your component more testable. It also has the effect that if parsedInput or userInput changed for some other reason other than through v-model, then the watch would be called.


[#55654] Thursday, December 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidanl

Total Points: 156
Total Questions: 102
Total Answers: 112

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;