我有一个有一个文本输入v-model和一个v-on:change连接到它。当用户输入时,我在其中更新一个数组,data并且UI绑定到该数组。我也想调用一个方法来通过AJAX发送用户输入。发送到服务器的数据是计算属性的结果。
<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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
是否同时使用了Vue v-model和v-on:change最佳实践Vue?
竖起大拇指@kmc0590000 作为补充。使用 watch,您还可以查看之前的状态和当前状态。它们作为参数传递。
v-model只是语法糖,并执行以下操作:
<input :value="userInput" @input="change">
Run Code Online (Sandbox Code Playgroud)
你也可以用@change代替v-on:和:value代替v-bind:value.
在第 6 行 ( v-on:change="process()") 中,您可以删除括号。输入事件作为参数提供给您的方法,您可以直接访问属性。( https://vuejs.org/v2/guide/events.html#Method-Event-Handlers )
我建议您使用手表而不是手表v-on:change。在视图中,您将删除v-on:change。任何时间parsedInput更改(由于userInput更改),都会调用watch函数。监视函数的名称必须与计算/数据属性的名称相同。
new Vue({
computed: {
parsedInput () {
return parse(this.userInput)
}
}
methods: {
process () {
serverProcess(this.parsedInput);
}
},
watch: {
parsedInput() {
this.process()
}
}
})
Run Code Online (Sandbox Code Playgroud)
您可以在这里阅读有关手表的更多信息https://vuejs.org/v2/guide/computed.html#Watchers
IMO,这样做更好,因为您是通过代码而不是视图来描述应用程序的更多行为。这将使您的组件更具可测试性。它也有,如果影响parsedInput或userInput改变不是通过V模型等一些其他的原因,则手表将被调用。