Vue數(shù)據(jù)更新視圖未更新的幾種解決方案
一、問題描述
在Vue項目中,有時我們會遇到數(shù)據(jù)更新了,但是視圖沒有更新的情況,這是因為Vue使用的是異步更新的方式,如果數(shù)據(jù)變化時視圖沒有立即響應(yīng),則一般都會考慮使用以下幾種解決方案:
- 方案一:使用
watch監(jiān)聽對象屬性變化
<template>
<div>
<h3>{{userInfo.name}}</h3>
<button @click="changeUserName">點擊我改變用戶名</button>
</div>
</template>
<script>
export default {
data(){
return {
userInfo: {
name: '張三',
age: 16
}
}
},
watch:{
'userInfo.name': {
handler(newValue, oldValue) {
console.log('用戶名變化了,新值:' + newValue + ',舊值:' + oldValue);
},
immediate: true,
deep: true
}
},
methods:{
changeUserName(){
// 假設(shè)異步請求修改用戶名
const newUserName = '李四';
this.userInfo.name = newUserName;
}
}
}
</script>
- 方案二:使用
this.$set()強制更新響應(yīng)式變量
// 定義數(shù)據(jù)對象:
obj: { name: "小明", age: 18, },
// 基本語法:
this.$set(需要改變的對象,"需要改變的對象屬性","新值")
示例如下:
<template>
<div>
<h3>{{initList.message}}</h3>
<button @click="changeMessage">點擊我改變message值</button>
</div>
</template>
<script>
export default {
data(){
return {
initList: {
message: 'hello'
},
}
},
methods:{
changeMessage(){
// 假設(shè)是異步調(diào)用獲取到了新的message值
const newMessage='world';
this.$set(this.initList, 'message', newMessage);
}
}
}
</script>
- 方案三:使用
this.$forceUpdate()強制性重新渲染
methods: {
// 在某些情況下需要強制重新渲染組件
forceRerender() {
// 調(diào)用 $forceUpdate()方法
this.$forceUpdate();
}
}
但是,在項目中,如果以上方案均無效,比如由于無法使用watch或this.$set()實現(xiàn)所需功能,或者使用后會使代碼變得更復(fù)雜、冗余;同時層級太多或其他原因?qū)е?code>this.$forceUpdate()也不起作用,那么還有什么方案可以解決視圖不更新的問題呢?
二、解決方案
為確保視圖更新,可以先將數(shù)據(jù)賦值后再清空,最后在this.$nextTick()中處理數(shù)據(jù),并重新賦值。代碼示例如下:
// 為確保視圖更新,先將數(shù)據(jù)重新賦值給一個變量,然后再清空
const details = this.detailsList;
this.detailsList = [];
// 處理數(shù)據(jù),并重新賦值
this.$nextTick(() => {
// 處理數(shù)據(jù)
const detailsList = this.formatList(details, data.playCourseChapterId);
// 重新賦值
this.detailsList = Object.assign([], detailsList);
})
這時,數(shù)據(jù)更新的同時,視圖也會同步更新。
備注:
我這邊的項目中,是因為層級循環(huán)太多,導(dǎo)致以上三種方案均不起作用。只有最后這種方案可以解決視圖不更新的問題。
以上,希望對大家有幫助!
到此這篇關(guān)于Vue數(shù)據(jù)更新視圖未更新的幾種解決方案的文章就介紹到這了,更多相關(guān)Vue數(shù)據(jù)更新視圖未更新內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VueCli生產(chǎn)環(huán)境打包部署跨域失敗的解決
這篇文章主要介紹了VueCli生產(chǎn)環(huán)境打包部署跨域失敗的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

