vue的文档中有关于reactive()局限性的描述,这里用自己的方式展现出来。
1.先写好一个测试网页
2.点击 reactive 添加 可以看到控制台输出了信息 并且成功添加
3.点击 reactive 赋值 可以看到控制台输出了信息 但是并没有赋值,可见此时响应式连接丢失
4. 点击ref 添加 可以看到这里reactive更新了数据
5.再多次点击 reactive 添加 可见reactive数据没有更新
6.最后点击 ref 赋值 可见 reactive数据又更新了
个人总结:ref数据的修改会触发一次数据更新,这个数据更新会使所有没有响应式连接的数据也更新。
测试页面代码如下:
<script setup>
import { ref, reactive } from "vue";
let a = ref(["初始"]);
let b = reactive(["初始"]);
const log = ["ref 添加", "ref 赋值", "reactive 添加", "reactive 赋值"];
const add = () => "添加";
const equal = () => ["赋值"];
</script>
<template>
<div>
<h2 style="margin-right: 100px">
ref
<button
@click="
() => {
a.push(add());
console.log(log[0]);
}
">
ref 添加
</button>
<button
@click="
() => {
a = equal();
console.log(log[1]);
}
">
ref 赋值
</button>
</h2>
{{ a }}
<h2 style="margin-right: 100px">
reactive
<button
@click="
() => {
b.push(add());
console.log(log[2]);
}
">
reactive 添加
</button>
<button
@click="
() => {
b = equal();
console.log(log[3]);
}
">
reactive 赋值
</button>
</h2>
{{ b }}
</div>
</template>