computed、watcher和methods的异同
1、方法执行
computed属性基于他所依赖的数据进行缓存(如果它依赖的数据没有变化,多次调用返回之前计算结果,不会每次都重复执行);
watcher属性里面的方法当需要的数据发生变化时执行。
methods属性里面的方法在绑定事件的dom触发时执行(触发一次,执行一次)
2、调用方法
computed的属性与data的属性调用方式一样,可以用{{}}。
<div id="example"> <p>初始message:{{message}}</p> <p>计算后的message:{{reversedMessage}}</p> </div>
var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { // 一个 computed 属性的 getter 函数 reversedMessage: function () { // `this` 指向 vm 实例 return this.message.split('').reverse().join('') } } })watcher的属性命名要与data属性的属性名对应(监控question变量的变化,watcher属性就要用question命名)
<div id="watch-example"> <p> 问一个答案是 yes/no 的问题: <input v-model="question"> </p> <p>{{ answer }}</p> </div>
<!-- 对于 ajax 库(ajax libraries)和通用工具方法的集合(collections of general-purpose utility methods)来说, --> <!-- 由于已经存在大量与其相关的生态系统, --> <!-- 因此 Vue 核心无需重新创造,以保持轻量的文件体积。 --> <!-- 同时这也可以使你自由随意地选择自己最熟悉的。 --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script> <script> var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: '你要先提出问题,我才能给你答案!' }, watch: { // 只要 question 发生改变,此函数就会执行 question: function (newQuestion, oldQuestion) { this.answer = '等待输入停止……' this.getAnswer() } }, methods: { // _.debounce 是由 lodash 提供的函数, // 在运行特别消耗性能的操作时, // 可以使用 _.debounce 来限制频率。 // 在下面这种场景中,我们需要限制访问 yesno.wtf/api 的频率, // 等到用户输入完毕之后,ajax 请求才会发出。 // 想要了解更多关于 _.debounce 函数(以及与它类似的 _.throttle)的详细信息, // 请访问:https://lodash.com/docs#debounce getAnswer: _.debounce( function () { if (this.question.indexOf('?') === -1) { this.answer = '问题通常需要包含一个中文问号。;-)' return } this.answer = '思考中……' var vm = this axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = '错误!API 无法处理。' + error }) }, // 这是用户停止输入操作后所等待的毫秒数。 // (译者注:500毫秒之内,用户继续输入,则重新计时) 500 ) } }) </script>
methods的属性可以随意命名,调用是通过事件绑定机制来进行的(也可以传参,获取事件信息用$event)。
new Vue({ el: '#example-3', methods: { say: function (message) { alert(message) } } })
<div id="example-3"> <button v-on:click="say('hi')">Say hi</button> <button v-on:click="say('what')">Say what</button> </div>