我觉得应该将观察者作为Vue的不得已而为之。我知道计算属性比观察者更受青睐。但是,有时您可以使用观察者或@change来执行相同的操作。我觉得在以下情况下,事件是执行操作的更好且更明确的方式:
来自VueJS Guide - Computed Properties and Watchers
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
var watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
watch: {
// whenever question changes, this function will run
question: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
_.debounce(this.getAnswer, 500)
}
},
...
}
或者您可以使用@change或@input事件来做到这一点:
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question" @change="getAnswer">
</p>
<p>{{ answer }}</p>
</div>
var watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
methods: {
// whenever question changes, this function will run
getAnswer: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
_.debounce(this.getAnswer, 500)
}
},
...
}
我不确定为什么在@change或类似事件中使用观察者。我觉得在这种情况下最好使用事件,因为它更明确。
所以我的问题是: