Skip to content

$set()

在vue的实例方法中,$set可以更新对象数据或是数组,有时在实际的开发过程中,对象的数据可能会没有及时地更新,导致页面渲染的值还是旧值,这个时候就可以使用$set去重新更新下数据。

(1)参数1: 要更改的数据源(可以是一个对象或者数组)

(2)参数2: 要更改的具体数据 (索引)

(3)参数3: 重新赋的值(any) $set()更新数组

js
<template>
  <div class="demo">
    <ul>
      <li v-for="(item, index) of TypeList" :key="index">
        {{ item }}
      </li>
    </ul>
    <button @click="add">添加</button>
  </div>
</template>

<script>
export default {
  name: "demo",
  data() {
    return {
      TypeList:['苹果','香蕉','草莓']
    };
  },
  created() {
    console.log('created生命周期:',this.TypeList);
  },
  updated() {
    console.log('updated生命周期:',this.TypeList);
  },
  methods: {
    add() {
      this.$set(this.TypeList, 1, '榴莲');

      打印:  typeList:['苹果','榴莲','草莓']
    },
  },
};
</script>
<template>
  <div class="demo">
    <ul>
      <li v-for="(item, index) of TypeList" :key="index">
        {{ item }}
      </li>
    </ul>
    <button @click="add">添加</button>
  </div>
</template>

<script>
export default {
  name: "demo",
  data() {
    return {
      TypeList:['苹果','香蕉','草莓']
    };
  },
  created() {
    console.log('created生命周期:',this.TypeList);
  },
  updated() {
    console.log('updated生命周期:',this.TypeList);
  },
  methods: {
    add() {
      this.$set(this.TypeList, 1, '榴莲');

      打印:  typeList:['苹果','榴莲','草莓']
    },
  },
};
</script>

#2.2 通过数组的操作方法去修改(push(),pop(),splice()等

修改数组元素个人喜欢spice()方法

(1)参数1: 插入的位置索引号

(2)参数2: 删除元素的个数

(3)参数3: 插入的元素

js
<template>
  <div class="demo">
    <ul>
      <li v-for="(item, index) of typeList" :key="index">
        {{ item }}
      </li>
    </ul>
    <button @click="add">添加</button>
  </div>
</template>

<script>
export default {
  name: "demo",
  data() {
    return {
      typeList:['苹果','香蕉','草莓']
    };
  },
  created() {
    console.log('created生命周期:',this.typeList);
  },
  updated() {
    console.log('updated生命周期:',this.typeList);
  },
  methods: {
    add() {
    //   this.typeList.push('冬瓜')
    this.typeList.splice(1,1,'冬瓜')
    },
  },
};
</script>
<template>
  <div class="demo">
    <ul>
      <li v-for="(item, index) of typeList" :key="index">
        {{ item }}
      </li>
    </ul>
    <button @click="add">添加</button>
  </div>
</template>

<script>
export default {
  name: "demo",
  data() {
    return {
      typeList:['苹果','香蕉','草莓']
    };
  },
  created() {
    console.log('created生命周期:',this.typeList);
  },
  updated() {
    console.log('updated生命周期:',this.typeList);
  },
  methods: {
    add() {
    //   this.typeList.push('冬瓜')
    this.typeList.splice(1,1,'冬瓜')
    },
  },
};
</script>

反快餐主义者