vue3 this.$set()?

7,928 阅读1分钟

在Vue2中,修改某一些数据,视图是不能及时重新渲染的

<div v-for="(item, index) in list" :key="index">{{ item }}</div>
data() {
    return {
        list: ['你', '我', '它'],
    }
},
mounted() {
   this.list[2] = '他';
   // vue新方法
   this.$set(this.list, 2, '他')
},

为什么不能直接修改?为什么要这么鸡肋?
原因就是 Vue2 中的数据响应式是利用 object.definedProperty()实现的,它是无法深层监听数据的变化的

Vue3 this.$set()?

而Vue3,利用的是ES6的proxy,对数据响应式进行一个数据的代理

setup() {
    const list = ['你', '我', '它'];
    return {
        list,
    }
},
mounted() {
   // 无更新
   this.list[2] = '他';
},

Vue3 中 新出的 reactivity API:

  1. reactive
  2. readonly
  3. ref
  4. computed

如果想要让一个对象变为响应式数据,可以使用reactive或ref

setup() {
    const list = reactive(['你', '我', '它']);
    return {
        list,
    }
}
mounted() {
   // 完成更新
   this.list[2] = '他';
},

因此无需this.$set()

  1. ref和reactive区别:

    (1如果在template里使用的是ref类型的数据, 那么Vue会自动帮我们添加.value (2如果在template里使用的是reactive类型的数据, 那么Vue不会自动帮我们添加.value

  2. Vue是如何决定是否需要自动添加.value的Vue在解析数据之前, 会自动判断这个数据是否是ref类型的,如果是就自动添加.value, 如果不是就不自动添加.value

  3. Vue是如何判断当前的数据是否是ref类型的通过当前数据的__v_ref来判断的如果有这个私有的属性, 并且取值为true, 那么就代表是一个ref类型的数据

<template>
  <div v-for="(item, index) in seachList" :key="index">{{ item }}</div>
</template>
<script lang="ts" setup>
import { ref, toRefs, reactive } from 'vue';

const seachList = ref(['你', '我', '它']);
const textList = reactive({value: 12});

const seachListFn = () => {
    seachList.value[2] = '他';
    textList.value = 90000;
    console.log(seachList, 'seachList')
    console.log(textList, 'textList')
}
// 初次进入页面
seachListFn();
</script>

ref注意,vue模板中没有seachList.value,因为ref类型的数据有isRef属性,底层自动会将.value加上

reactive页面还是个对象数据,因为是reactive类型数据,没有isRef属性,vue不会自动在模板添加.value, 所以我们需要手动在模板添加age.value

console.log(isRef(treeData));
console.log(isReactive(treeData));
// 判断数据到底是ref还是reactive

【有需修改注意,请留言】