美文网首页让前端飞优美编程
前端碰撞室之vue2.5中数组到底啥时候会有更新问题

前端碰撞室之vue2.5中数组到底啥时候会有更新问题

作者: 小遁哥 | 来源:发表于2020-05-10 00:13 被阅读0次

看一个例子:

<template>
  <div>
    <div v-for="(item, index) in list" :key="item.id">
      <span>{{ item.name }}</span> | <span>{{ item.age }}</span> |
      <Button @click="onAgeShow(item, index)">改变年龄</Button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          id: "1",
          name: "小红",
          age: 1,
        },
        {
          id: "2",
          name: "小明",
        },
      ],
    };
  },
  methods: {
    onAgeShow(item, index) {
      item.age = 14;
    },
  },
};
</script>

界面是这样的

点第一个会显示年龄,点第二个则不会

因为vue2.5 是基于Object.defineProperty(),没这个属性就劫持不了,改变时也触发不了DOM更新

改成下面可以更新

    onAgeShow(item, index) {
      this.list.splice(index, 1, { ...item, age: 12 });
    },

vue拦截了数组原型链上的一些方法

用数组原型链上的splice就不行了

    onAgeShow(item, index) {
      Array.prototype.splice.call(this.list, index, 1, { ...item, age: 12 });
    },

所以,像lodash 一些库去操作就会出问题

改变引用也可以解决

    onAgeShow(item, index) {
      item.age = 13;
      this.list = [...this.list];
    }

结语

很多情况下确实不好提前声明所有的属性...
早点用3.0 吧

相关文章

网友评论

    本文标题:前端碰撞室之vue2.5中数组到底啥时候会有更新问题

    本文链接:https://www.haomeiwen.com/subject/zjetnhtx.html