Vue2 给对象新增和删除属性

Vue2的响应式原理

<script>
import Vue from 'vue'
export default{
  name: 'App',
  data() {
    return{
      person:{
        name: "张三",
        age: 18,
        hobby:["吃饭", "睡觉"]
      }
    }  
  },
  methods: {
    addSex() {
      console.log(this.person.sex)//undefined
      this.person.sex = '女'
      console.log(this.person.sex)//女
      //以上方法,确实给person添加了 一个sex属性,但是没有在页面更新.因为defindeProperty方法监测不到
      //使用this.$set()方法,或者Vue.set()方法
      this.$set(this.person, 'sex', '男')
      Vue.set(this.person, 'sex', 男)
    },

    deleteName(){ 
      delete this.person.name//此方法也不行
      this.$delete(this.person, 'name');
      Vue.delete(this.person, 'name')
      
    },
    updateFirstHobby(){
      this.person.hobby[0] = '听歌'//修改了person.hobby[0],但是界面不更新。
      this.$set(this.person.hobby, 0, '听歌')//可以
      this.person.hobby.splice(0,1)//也可以,因为调用了数组身上的变更方法
    }
  }

}

</scritp>
posted @ 2022-08-09 23:44  wjwdive  阅读(976)  评论(0编辑  收藏  举报