gpt4 book ai didi

javascript - 这是 v-on :change? 的正确用法吗

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:03 28 4
gpt4 key购买 nike

我有一个附加了 v-modelv-on:change 的文本输入。当用户输入时,我更新 data 中的一个数组,并且 UI 绑定(bind)到该数组。我还想调用一个方法通过 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);
}
}
});

同时使用 v-modelv-on:change 是 Vue 的最佳实践吗?

最佳答案

我建议使用 watch 而不是 v-on:change。在 View 中,您将删除 v-on:change。任何时候 parsedInput 发生变化(由于 userInput 发生变化),都会调用 watch 函数。监视函数的名称与计算/数据属性的名称相同很重要。

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

您可以在这里阅读更多关于 watch 的信息 https://v2.vuejs.org/v2/guide/computed.html#Watchers

IMO,这更好,因为您通过代码而不是 View 来描述应用程序的更多行为。这将使您的组件更易于测试。它还具有这样的效果,即如果 parsedInputuserInput 由于某些其他原因而不是通过 v-model 发生更改,则会调用 watch。

关于javascript - 这是 v-on :change? 的正确用法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870889/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com