网上watch
和$nextTick()
解释比较复杂,涉及到promise,h5的dom发生变化的新api等复杂代码,下列就是两个参考。
【watch原理】
【$nextTick()】javascript
首先,看遇到问题代码:html
<template> <div> <button @click="changeList">我要变成童话里大灰狼,嘿嘿!</button> </div> </template> <script> export default { data () { return { isfirst: true, num: 0 }; }, watch: { 'num': function (val) { if (val > 0 && this.isfirst) { console.log('我改变了'); // 是不会之执行的 } console.log('我又改变了'); // 只会执行之一段 } }, methods: { changeList () { this.num += 1; this.isfirst = false; } } } </script>
简单用watch的原理实现上述代码,以下:vue
// es6 class Parent () { // ... get num () { return this.val; } set num (val) { this.val = val; // watch 原始把回调放在这里 isfirst && cb(); // 步骤1 } // ... } // es5的写法 defindeProperty(new Parent(), 'num', { get: () => this.val, set (val) { this.val = val; // watch 原始把回调放在这里 isfirst && cb(); // 步骤1 } }); const parent = new Parent(); parent.num = 2; isfirst = false; // 步骤2
先执行步骤1,还步骤2?答案是步骤 2。我想要的就结果是步骤1执行完,在执行步骤2。java
vue提供vm.$nextTick(fn(){})
。es6
methods: { changeList () { this.num += 1; this.$next(()=> { this.isfirst = false; }); } }