在Vue官方文檔中指出,$forceUpdate
具有強(qiáng)制刷新的作用。
那在vue框架中,如果data
中有一個變量:age,修改他,頁面會自動更新。
但如果data
中的變量為數(shù)組或?qū)ο?,我們直接去給某個對象或數(shù)組添加屬性,頁面是識別不到的?
<template>
<p>{{userInfo.name}}</p>
<button @click="updateName">修改userInfo</button>
</template>
<script>
data(){
return{
userInfo:{name:'小明'}
}
},
methods:{
updateName(){
this.userInfo.name='小紅'
}
}
</script>
在updateName
函數(shù)中,我們嘗試給userInfo
對象修改值,發(fā)現(xiàn)頁面其實并沒有變化
那這時候有兩種解決方法:
方法一:文章來源:http://www.zghlxwxcb.cn/news/detail-632953.html
methods:{
updateName(){
this.userInfo.name='小紅'//在此時,確實已經(jīng)將userInfo對象修改完成
console.log(this.userInfo.name);//輸出結(jié)果: 小紅
this.$forceUpdate();//在這里,強(qiáng)制刷新之后,頁面的結(jié)果變?yōu)?小紅'
}
}
方法二:文章來源地址http://www.zghlxwxcb.cn/news/detail-632953.html
methods:{
updateName(){
this.$set('userInfo',name,'小紅');
}
}
到了這里,關(guān)于Vue中,$forceUpdate()的使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!