實例的 $nextTick
方法用於在下次 DOM 更新循環結束之后執行延遲回調。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>test</title> 5 <script type="text/javascript" src="https://vuejs.org/js/vue.js"></script> 6 </head> 7 <body> 8 <!-- <div id="app"> --> 9 <button id="app" ref="tar" type="button" v-on:click="testClick">{{ content }}</button> 10 <!-- <button ref="tar" type="button" >{{ content }}</button> --> 11 <!-- </div> --> 12 </body> 13 <script type="text/javascript"> 14 var app = new Vue ({ 15 el:'#app', 16 data(){ 17 return { 18 content:'初始值' 19 } 20 }, 21 methods:{ 22 testClick(){ 23 this.content = '改變了的值' 24 //這會直接打印的話, 由於dom元素還沒有更新, 因此打印出來的還是未改變之前的值; 初始值 25 console.log(this.$refs.tar.innerText) //添加ref屬性,便於查找 26 }, 27 testClick2(){ 28 this.content='改變了的值2' 29 this.$nextTick(()=>{ 30 //dom元素更新后執行, 因此此處能正確打印出更改之后的值; 改變了的值2 31 console.log(this.$refs.tar.innerText) 32 }) 33 } 34 } 35 }) 36 </script> 37 </html>
button調用testClick與testClick2,顯示分別為【改變了的值】與【改變了的值2】,打印console分別為【初始值】與【改變了的值2】