下面用Computed和Methods实现同一个功能:
<!-- 计算属性示例 -->
<p>Computed reversed message: "{{ reversedMessage }}"</p>
<script>
// ...
computed: {
reversedMessage: function () {
return this.message.split(‘‘).reverse().join(‘‘);
}
</script>
<!-- 方法示例 -->
<p>Reversed message: "{{ reversedMessage() }}"</p>
<script>
// ...
methods: {
reversedMessage: function () {
return this.message.split(‘‘).reverse().join(‘‘);
}
}
</script>
具体分析如下:
侦听属性是一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。
当你有一些数据需要随着其它数据变动而变动时,或者当需要在数据变化时执行异步或开销较大的操作时,你可以使用 watch。
在下面这个示例中,使用 watch 选项允许我们执行异步操作 (访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的。
<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: {
// 如果 `question` 发生改变,这个函数就会运行
question: function (newQuestion, oldQuestion) {
this.answer = ‘Waiting for you to stop typing...‘
this.debouncedGetAnswer()
}
},
created: function () {
this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
},
methods: {
getAnswer: function () {
if (this.question.indexOf(‘?‘) === -1) {
this.answer = ‘Questions usually contain a question mark. ;-)‘
return
}
this.answer = ‘Thinking...‘
var vm = this
axios.get(‘https://yesno.wtf/api‘)
.then(function (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = ‘Error! Could not reach the API. ‘ + error
})
}
}
})
Vue里的计算属性(computed)、方法(methods)和侦听属性(watch)的区别与使用场景
原文:https://www.cnblogs.com/Nullc/p/13209887.html