強制更新($forceUpdate) 點擊打開視頻講解更加詳細 在vue中,如果data中有基本數據類型變數:age,修改他,頁面會自動更新。 但如果data中的變數為數組或對象(引用數據類型),我們直接去給某個對象或數組添加屬性,頁面是識別不到的,不會同步更新; <template> <div i ...
強制更新($forceUpdate)
在vue中,如果data中有基本數據類型變數:age,修改他,頁面會自動更新。
但如果data中的變數為數組或對象(引用數據類型),我們直接去給某個對象或數組添加屬性,頁面是識別不到的,不會同步更新;
<template>
<div id="app">
name:<p>{{userInfo.name}}</p>
age:<p>{{userInfo.age}}</p>
<button @click="updateName">增加age屬性</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
userInfo:{
name:'末晨曦吖'
}
}
},
mounted() {
},
components:{
},
methods:{
updateName(){
this.userInfo.age = 18
}
}
}
</script>
<style scoped>
</style>
我們嘗試給userInfo對象添加屬性值,發現頁面其實並沒有變化
<template>
<div id="app">
name:<p>{{userInfo.name}}</p>
age:<p>{{userInfo.age}}</p>
<div v-for="(item,index) in list" :key="index">{{ item.name }} --- {{ item.age }}</div>
<button @click="updateName">增加age屬性</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
userInfo:{
name:'末晨曦吖'
},
list:[
{ name:'末' }
]
}
},
mounted() {
},
components:{
},
methods:{
updateName(){
// 對象
// this.userInfo.age = 18
// this.$forceUpdate() // 第一種解決方式: this.$forceUpdate(); 強制刷新 同等效果的:window.location.reload() 不推薦
// this.$set(this.userInfo,'age',18) // 第二種解決方式 推薦使用
// 數組
// this.list[0].age = 18
// this.$forceUpdate()
// this.$set(this.list[0],'age',18)
}
}
}
</script>
<style scoped>
</style>
通過 v-once 創建低開銷的靜態組件
渲染普通的 HTML 元素在 Vue 中是非常快速的,但有的時候你可能有一個組件,這個組件包含了大量靜態內容。在這種情況下,你可以在根元素上添加 v-once attribute 以確保這些內容只計算一次然後緩存起來,就像這樣:
Vue.component('terms-of-service', {
template: `
<div v-once>
<h1>Terms of Service</h1>
... a lot of static content ...
</div>
`
})