响应式基础
ref()
为什么要使用 ref?Ref 可以持有任何类型的值,当一个 ref 被修改时,它会触发追踪它的组件的一次重新渲染。
<script setup>
import { ref } from "vue";
const obj = ref({
nested: { count: 0 },
arr: ["foo", "bar"],
});
function mutateDeeply() {
// 以下都会按照期望工作
obj.value.nested.count++;
obj.value.arr.push("baz");
}
</script>
reactive()
reactive() 将使对象本身具有响应性,返回的是一个原始对象的 Proxy
<script setup>
import { reactive } from "vue";
const state = reactive({ count: 0 });
</script>
由于这些限制,我们建议使用 ref() 了解 ref 何时自动解包(只有顶级的 ref 属性才会被解包。)
参考链接
https://cn.vuejs.org/guide/essentials/reactivity-fundamentals.html#ref