分享

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

 千锋Python学堂 2020-07-14

数据丢失是框架的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) // 修改对象的数据

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多