ITPub博客

首页 > IT职业 > IT图书 > vue数据丢失的4中情况&解决方法

vue数据丢失的4中情况&解决方法

IT图书 作者:robert95 时间:2021-09-09 10:44:28 0 删除 编辑

数据丢失是框架的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>

解决方法:
第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)  // 修改对象的数据

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3263/viewspace-2825762/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    87
  • 访问量
    672