温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-10 14:55:55 来源:ITPUB博客 阅读:238 作者:千锋Python唐小强 栏目:web开发

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI