Vue中 this.$set的用法

Vue中this.$set的用法

Vue.set( target, propertyName/index, value )

参数

{Object | Array} target

{string | number} propertyName/index

{any} value

<template>
  <div class="page" id="app">
    <button @click="add">设置</button>
    <ol>
      <li v-for="(item, index) in arr" :key="index">{{ item.name }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        { name: "Hanmeimei", age: 21 },
        { name: "Lilei", age: 21 },
      ],
    };
  },
  mounted() {
    this.arr[2] = { name: "小明", age: 23 }; //数组的值发生了变化 但视图没有更改
  },
  methods: {
    add() {
      this.$set(this.arr, 2, { name: "小明", age: 23 }); //$set 触发视图更改
    },
  },
};
</script>

<style>
</style>

你可能感兴趣的:(前端vue,vue)