vue深入响应式原理 - 对象- 数组

  1. 项目结构
    在这里插入图片描述
    2.fater.vue
<template>
  <div>
    <h1>{
    
    {
    
    man}}</h1>
    <button @click="changeObj">添加对象属性</button>
    <button @click="changeObjAddr">改变对象的地址</button>
    <hr />
    <h1>{
    
    {
    
    arr}}</h1>
    <button @click="changeArr">改变数组</button>
    <hr />
    <h3>
      <son :name="man" :arr="arr"></son>
    </h3>
  </div>
</template>

<script>
import son from "./son";
export default {
    
    
  components: {
    
    
    son
  },
  data() {
    
    
    return {
    
    
      man: {
    
    
        name: "张"
      },
      arr: [1, 2, 3, 4, 5, 6]
    };
  },
  methods: {
    
    
    changeObj() {
    
    
      // 1.vue对象的响应式
      //1.1为对象添加某个属性
      // Vue.set(object, propertyName, value) /*官网方法*/
      // console.log('this.man.age:', this.man.age === undefined)
      // if(this.man.age === undefined){
    
    
      //     let age = 0
      //      this.$set(this.man,'age',age)
      // }else{
    
    
      //     this.man.age+=1
      // }
      //   或者
      let age = this.man.age === undefined ? 0 : (this.man.age += 1);
      this.$set(this.man, "age", age);

      //1.2为对象添加多个属性
      // // 代替 `Object.assign(this.someObject, { a: 1, b: 2 })`
      // this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 }) /*官网方法*/
      this.man = Object.assign({
    
    }, this.man, {
    
     age: 3, addr: "重庆" });
    },

    changeObjAddr() {
    
    
      this.man.addr = "北京";
    },

    changeArr() {
    
    
      // 2.vue数组的响应式
      //2.1改变数组的某一项
      // vm.$set(vm.items, indexOfItem, newValue) /*官网方法*/
      this.$set(this.arr, this.arr.length - 1, 9);

      //2.2改变数组的长度
      // vm.items.splice(newLength) /*官网方法*/
    //   this.arr.splice(5);
    }
  }
};
</script>

3.son.vue

<template>
    <div>
       {
    
    {
    
    name}}  
       <br>
       {
    
    {
    
    arr}}  
    </div>
</template>

<script>
export default {
    
    
  props:['name','arr']
}   
</script>

4.结果
在这里插入图片描述
vue官网 添加链接描述

猜你喜欢

转载自blog.csdn.net/weixin_43413047/article/details/107140330