<body> <script src='https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js'></script> <div id='myApp'> <h1 ref="h1">{{name}}</h1> </div> <script> new Vue({ el: '#myApp', data: { name: '张三' }, mounted() { this.name = "李四"; console.log(1, this.name, this.$refs.h1.innerText)//1 李四 张三 this.name = "小明"; console.log(2, this.name, this.$refs.h1.innerText)//2 小明 张三 // 当vue中data数据更新后, DOM更新并及时, 因为虚拟DOM执行计算和操作更新属于异步更新, 每一次dom的更新都需要在异步更新队列中等待, 等到下一帧界面刷新时,统一更新 // 如何保证data数据修改后,dom显示数据和data保持一致? // vue中提供了一个异步函数, 用于检测dom异步更新队列, 当dom异步更新结束,会调用这个函数的回调, 此时我们在回调中读取dom数据,即最新数据 this.$nextTick(()=>{ console.log(3, this.name, this.$refs.h1.innerText) // 3 王五 王五 }) this.name = "王五"; console.log(4, this.name, this.$refs.h1.innerText)//4 王五 张三 }, }) </script></body>