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是可以直接触发页面更新的

 

posted @ 2019-10-27 13:03  丿离水的鱼  阅读(2780)  评论(0编辑  收藏  举报