vue ref实现
Vue 中 ref 的实现
在 Vue 中,ref 是一个用于创建响应式引用的 API,适用于基本类型和对象。以下是 ref 的核心实现原理和使用方法。
基本实现原理
ref 通过 Reactive 系统将一个值包装为响应式对象。内部使用 value 属性存储实际值,并通过 getter 和 setter 实现依赖收集和触发更新。

function ref(value) {
return {
get value() {
track(this, 'value'); // 依赖收集
return value;
},
set value(newValue) {
value = newValue;
trigger(this, 'value'); // 触发更新
}
};
}
在模板中的使用
在模板中直接使用 ref 时,Vue 会自动解包 .value,无需显式调用。
<template>
<div>{{ count }}</div>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
在组合式 API 中的使用
在 JavaScript 中操作 ref 时,需要通过 .value 访问或修改值。

import { ref } from 'vue';
const count = ref(0);
function increment() {
count.value++; // 修改值
}
ref 与 reactive 的区别
ref适用于基本类型(如number、string)或对象引用,通过.value访问。reactive仅适用于对象,直接访问属性,无需.value。
const objRef = ref({ foo: 1 });
objRef.value.foo = 2; // 需要 .value
const objReactive = reactive({ foo: 1 });
objReactive.foo = 2; // 直接修改
ref 的进阶用法
通过 unref 可以简化逻辑,避免重复判断 .value。
import { ref, unref } from 'vue';
const maybeRef = ref(0);
const value = unref(maybeRef); // 自动解包
在响应式对象中使用 ref
当 ref 被嵌套在 reactive 对象中时,会自动解包 .value。
const count = ref(0);
const state = reactive({ count });
console.log(state.count); // 直接访问,无需 .value






