数据丢失是框架的BUG,vue中的数据绑定是通过ES5中属性的特性实现的。所以没有设置特性的数据,就会丢失。以下mounted中的四种操作都会导致数据丢失。

<template>
  <div>
    <div>{{ colors }}</div>
    <div>{{ obj }}</div>
    <div>{{ intro }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      colors: ["red", "green", "blue"],
      obj: {},
    };
  },
  mounted() {
    // 1 数组中的值类型修改
    this.colors[1] = "pink";
    // 2 数组中的新成员
    this.colors[3] = "gold";
    // 3 对象中的新属性
    this.obj.size = 200;
    // 4 未初始化的数据
    this.intro = "111111";
  },
};
</script>

vue数据丢失的4中情况和解决方法(附视频教程)

 

解决方法:

第1,2种情况 使用新数组替换之前的老数组

this.colors = ["red", "pink", "blue","gold"]

第3种情况 使用新对象替换之前的老对象

this.obj = {siz: 200}

第4种情况 初始化这类数据即可

data() {
    return {
      colors: ["red", "green", "blue"],
      obj: {},
      intro: '' // 初始化info
    };
  },

除此之外,还可以使用vue提供的$set方法

this.$set(this.colors, 1, pink)  // 修改数组的数据
this.$set(this.obj, 'size', 200)  // 修改对象的数据

2020Vue全套教程全开源(强烈推荐)https://pan.baidu.com/s/15_Q2Mn_Vr_vL6PaJJ7ueGw

这是给课后的惊喜,熬夜录的,学习的伙伴可以留言!

Logo

前往低代码交流专区

更多推荐