vue 視圖不更新

$nextTick


image.png
<template>
  <section>
    <h1 ref="hello">{{ value }}</h1>
    <el-button type="danger" @click="get">點(diǎn)擊</el-button>
  </section>
</template>
<script>
  export default {
    data() {
      return {
        value: 'Hello World ~'
      };
    },
    methods: {
      get() {
        this.value = '你好啊';
        console.log(this.$refs['hello'].innerText);
        this.$nextTick(() => {
          console.log(this.$refs['hello'].innerText);
        });
      }
    },
    mounted() {
    },
    created() {
    }
  }
</script>
image.png

根據(jù)上面的例子可以看出,在方法里直接打印的話, 由于dom元素還沒有更新, 因此打印出來的還是未改變之前的值,而通過this.$nextTick()獲取到的值為dom更新之后的值

this.$set的用法

data中數(shù)據(jù),都是響應(yīng)式。也就是說,如果操作data中的數(shù)據(jù),視圖會(huì)實(shí)時(shí)更新;

但在實(shí)際開發(fā)中,遇到過一個(gè)坑:若data中數(shù)據(jù)類型較為復(fù)雜,方法methods中改變對象的屬性,視圖也就是頁面并不會(huì)改變

原因是vue監(jiān)聽不到數(shù)據(jù)類型特別復(fù)雜的屬性。

可以使用this.$set()來進(jìn)行強(qiáng)制更新,進(jìn)而解決問題

對象操作:

三個(gè)參數(shù):this.$set("改變的對象","改變的對象屬性","值")

數(shù)組操作:

三個(gè)參數(shù):this.$set("數(shù)組","下標(biāo)","值")

<template>
<div id="app2">
<p v-for="item in items" :key="item.id">{{item.message}}</p>
<button class="btn" @click="handClick()">更改數(shù)據(jù)</button> 
</div>
</template>

<script>
export default {
data() {
return {
items: [
{ message: "one", id: "1" },
{ message: "two", id: "2" },
{ message: "three", id: "3" }
]
};
},
mounted(){
this.items[0]={message:"測試",id:"4"}; //此時(shí)對象的值更改了,但是視圖沒有更新
this.$set(this.items,0,{message:"測試",id:"4"}); //$set可以觸發(fā)更新視圖
console.log(this.items)
},
methods: {
// 調(diào)用方法:Vue.set( target, key, value )

// target:要更改的數(shù)據(jù)源(可以是對象或者數(shù)組)

// key:要更改的具體數(shù)據(jù)

// value :重新賦的值
handClick() {
//Vue methods中的this 指向的是Vue的實(shí)例,這里可以直接在this中找到items
this.$set(this.items, 0, { message: "更改one的值", id: "0" });
},
}
};
</script>

<style>
</style>

參考:http://www.itdecent.cn/p/5fe073e36baf
參考:http://www.mamicode.com/info-detail-3063951.html
參考:https://www.cnblogs.com/lanshu123/p/11636377.html

監(jiān)聽參考:https://www.cnblogs.com/yesu/p/9546458.html

vue多層循環(huán),動(dòng)態(tài)改變數(shù)據(jù)后渲染的很慢或者不渲染
可在動(dòng)態(tài)改變數(shù)據(jù)的方法,第一行加上

this.$forceUpdate();

在使用Vue框架開發(fā)時(shí),在函數(shù)中改變了頁面中的某個(gè)值,在函數(shù)中查看是修改成功了,但在頁面中沒有及時(shí)刷新改變后的值,我是在使用多層v-for嵌套時(shí)出現(xiàn)這種問題的,

解決方法:運(yùn)用 this.$forceUpdate()強(qiáng)制刷新

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容