vue視圖不更新以及數據watch不到問題總結


1、源代碼

<template>
  <div>
    <div>
      <button @click="handleTestArr">testArr</button>
      <button @click="handleTestObj">testhandleTestObj</button>
      <p>testArr</p>
      <ul>
        <li v-for="arr in testArr" :key="arr">{{ arr }}</li>
      </ul>
      <a-divider></a-divider>
      <p>testObj</p>
      <p>a: {{ testObj.a }}</p>
      <p>b: {{ testObj.b }}</p>
      <a-divider></a-divider>
    </div>
  </div>
</template>
<script>
const obj = {
  a: 2,
  b: 4,
  c: 6,
}
const arr = ['a', 'b', 'c', 'd']
export default {
  data() {
    return {
      testArr: [1, 2, 3, 4, 5],
      testObj: {
        a: 1,
        b: 2,
      },
    }
  },
  methods: {
    handleTestArr() {
      this.testArr = arr
    },
    handleTestObj() {
      this.testObj = obj
    },
  },
  watch: {
    testArr() {
      console.log('arr')
    },
    testObj() {
      console.log('obj')
    },
  },
}
</script>

2、關於視圖

2.1、操作數組

    handleTestArr() {
      // this.testArr = arr//更新
      // this.testArr = [1, 2]//更新
      // this.testArr.push(6) /更新
      // this.testArr = this.testArr.slice(0, 2) //更新
       this.testArr[0] = 9 //視圖不更新,this.testArr已改變
    },
  • 總結:重新指定一個數組,視圖會更新,但是直接改變單個元素視圖不會更新
  • 解決方法:
    • 利用Array.splice方法來操作數組 this.testArr.splice(0, 1, 9)
    • 利用vue提供的接口$set來觸發試圖更新 this.$set(this.testArr,0,9)

2.2、操作對象

 handleTestObj() {
      // this.testObj = obj //更新
      // this.testObj = { a: 2, b: 3 } //更新
      // this.testObj['a'] = 2 //更新
      // this.testObj.a = 2 //更新
    },
  • 總結:操作對象的屬性,目前測試的幾種情況下,視圖都會變化

  • 某些未知情況下可能不更新視圖,同樣可以用$set來手動更新 this.$set("對象","對象屬性","值")

3、關於watch

3.1、操作數組

  handleTestArr() {
      // this.testArr = arr //觸發watch
      // this.testArr = [1, 2] //觸發watch
      // this.testArr.push(6) //觸發watch
      // this.testArr = this.testArr.slice(0, 2) //觸發watch
      // this.testArr[0] = 9 //不觸發watch
      this.$set(this.testArr, 0, 9)//觸發watch
    },
  • 總結:直接改變某個元素,不觸發watch(設置了deep:true也無效),可用過$set來處理

3.2、操作對象

    handleTestObj() {
      // this.testObj = obj //觸發watch
      // this.testObj = { a: 2, b: 3 } //觸發watch
      // this.testObj['a'] = 2 //不觸發watch
      // this.testObj.a = 2 //不觸發watch
    },
  • 總結:重新給對象賦值時能夠觸發watch,改變某個屬性時不能觸發

  • 解決方法:

    • 利用deep:true屬性深度監聽

    • 監聽具體的某個屬性:

       'testObj.a'(newVal, oldVal) {
            console.log('obj')
       },
      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM