vue.js中set和delete应用详解

基于vue2.x

结论

Vue.set:
作用:修改对象或者数组中的属性或者元素。
当watch检测的是对象或者数组时,set与watch的触发规律。

  1. 修改已经存在‘儿子’级的属性,不会触发watch事件。
  2. 修改‘孙子’级的属性,不会触发watch事件。
  3. 新增‘儿子’级的属性,触发watch事件。
  4. 新增‘孙子’级的属性,不会触发watch事件。
  5. 更新’孙子‘级的属性,不会触发watch事件。

Vue.delete:
作用:删除对象或者数组的属性或者元素。
当watch检测的是对象或者数组时,delete与watch的触发规律。

  1. 删除’儿子’级属性,触发watch事件。
  2. 删除’孙子’级属性,不会触发watch事件。

代码及运行结果

在这里插入图片描述

<template>
  <div class="home">
    <div>
      <button @click="updateGroundSonProperty">修改现有孙子属性</button>
      <button @click="addGroundSonProperty">新增孙子属性</button>
      <button @click="addChildProperty">新增儿子属性</button>
      <button @click="updateChildProperty">修改儿子属性</button>
      <button @click="deleteChildProperty">删除儿子属性</button>
      <button @click="deleteGrandsonProperty">删除孙子属性</button>
    </div>
    <div>
      {{data}}
    </div>
  </div>
</template>

<script>

export default {
  name: 'Home',
  components: {
  },
  data(){
    return {
      data:{
        child:{
          grandson:"aaa"
        },
        child2:''
      },
      eventStr:''
    }
  },
  watch:{
    data(){
      console.log('watch : ',this.eventStr);
      alert('1');
    }
  },
  methods:{
    updateGroundSonProperty(){
      this.eventStr = 'update grandson'
      console.log(this.eventStr);
      this.$set(this.data.child,'grandson','grandson');
    },
    addGroundSonProperty(){
      this.eventStr = 'add grandson'
      console.log(this.eventStr);
      this.$set(this.data.child,'grandson2','grandson2');
    },
    addChildProperty(){
      this.eventStr = 'add child'
      console.log(this.eventStr);
      this.$set(this.data,'child3','child3');
    },
    updateChildProperty(){
      this.eventStr = 'update child'
      console.log(this.eventStr);
      this.$set(this.data,'child2','child2');
    },
    deleteChildProperty(){
      this.eventStr = 'delete child'
      console.log(this.eventStr);
      this.$delete(this.data,'child2');
    },
    deleteGrandsonProperty(){
      this.eventStr = 'delete grandson2'
      console.log(this.eventStr);
      this.$delete(this.data.child,'grandson2');
    }
  }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值