vue data數據變化 頁面數據不更新問題


問題:

<template>
  <div class="container">
    <div v-for="(item, index) in arrList" :key="index">
      <span>{{ item.name }}-{{  item.age }}-{{ item.score }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      arrList: []
    }
  },
  created() {
    this.arrList = [
      {
        name: '小明',
        age: '20',
      },
      {
        name: '李華',
        age: '18'
      }
    ]
    this.getScore()
  },
  methods: {
    getScore() {
      let that = this
      setTimeout(() => {
        let res = [[59,59,59], [60,60,60]]
        res.forEach((item,  index) => {
          that.arrList[index].score = item
        })
      }, 1000)
    }
  }
}
</script>
View Code

頁面顯示:

 

 解決辦法:  使用this.$set()

methods: {
    getScore() {
      let that = this
      setTimeout(() => {
        let res = [[59,59,59], [60,60,60]]
        res.forEach((item,  index) => {
          // that.arrList[index].score = item

          // 下面兩種方法都可以
          // 1、使用this.$set()修改數據
          let arr = that.arrList[index]
          arr.score = item
          that.$set(that.arrList, that.arrList[index], arr)

          // 2、使用this.$set()添加數據
          that.$set(that.arrList[index], 'score', item)
        })
      }, 1000)
    }
  }
View Code

 

根據官方的文檔,使用數組的API是可以直接觸發頁面更新的

 


免責聲明!

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



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