Vue之this.$forceUpdate——強制更新資料
阿新 • • 發佈:2021-08-20
依據官網的生命週期,資料更新時,相關的元件生命週期包括beforeUpdate 、updated 。
生命週期 | 描述 |
beforeUpdate | 資料更新前呼叫。 |
updated | 由於資料更改導致的虛擬 DOM 重新渲染和打補丁,在這之後會呼叫該鉤子。 |
$forceUpdate 迫使元件或例項強制渲染。
示例
方法用於更新資料。當執行this.$forceUpdate() 時,重新重新整理資料。(輸出“更新了資料”)
1 <template> 2 <view class="flex flex-direction"> 3 <view>姓名:{{ student.name }}</view> 4View Code<view>年齡:{{ student.age }}</view> 5 <button class="margin-top cu-btn bg-blue" @click="addAge">年齡+1</button> 6 <button class="margin-top cu-btn bg-blue" @click="reload">更新資料</button> 7 </view> 8 </template> 9 10 <script> 11export default { 12 name:"comp-x", 13 data() { 14 return { 15 student:{ 16 name :'張三', 17 age:15 18 } 19 } 20 }, 21 updated:function(){ 22 console.log("更新了資料");23 }, 24 methods:{ 25 addAge: function(){ 26 this.student.age += 1; 27 }, 28 reload: function(){ 29 this.$forceUpdate(); 30 } 31 } 32 } 33 </script>