1. ref
- 基本类型响应式,访问和修改用
.value,这是硬性规定。
import { ref } from 'vue'
const count = ref(0)
count.value++
console.log(count.value)
忘了
.value,Vue 不会帮你自动补,自己背锅。
2. reactive
- 对象响应式,直接操作属性,方便快捷。
import { reactive } from 'vue'
const state = reactive({ a: 1, b: 2 })
state.a++
console.log(state.b)
改对象属性很简单,别指望它帮你换整个对象。
3. computed
- 计算属性,自动缓存,提高性能。
import { ref, computed } from 'vue'
const count = ref(2)
const double = computed(() => count.value * 2)
console.log(double.value)
count.value = 3
console.log(double.value)
省事又省力,CPU 表示感谢。
4. toRefs
- 解构 reactive 对象时,防止响应性丢失。
import { reactive, toRefs } from 'vue'
const state = reactive({ x: 1, y: 2 })
const { x, y } = toRefs(state)
console.log(x.value)
不用担心解构就断链了,放心用。
5. readonly
- 创建只读对象,防止修改。
import { reactive, readonly } from 'vue'
const state = reactive({ count: 0 })
const ro = readonly(state)
ro.count = 1 // 不允许改,控制严格
想改?报错提醒你,没商量。
6. shallowReactive
- 浅层响应式,只监听第一层。
import { shallowReactive } from 'vue'
const state = shallowReactive({ nested: { n: 0 } })
state.nested.n = 1 // 不触发响应
适合性能优化,内层别指望它管。
7. shallowRef
- 浅层 ref,只关注第一层。
import { shallowRef } from 'vue'
const obj = shallowRef({ count: 0 })
obj.value.count = 1 // 不触发响应
8. customRef
customRef允许我们手动控制 getter 和 setter 的行为,并且通过track和trigger精确控制依赖收集与更新触发的时机。
import { customRef } from 'vue'
const useDebouncedRef = (value, delay = 300) => {
let timeout
return customRef((track, trigger) => ({
get() {
track()
return value
},
set(newValue) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = newValue
trigger()
}, delay)
}
}))
}
// 使用方法
const keyword = useDebouncedRef('', 500)
防抖节流,响应式也能变聪明。
9. toRaw
- 取回原始对象,不被 Proxy 包裹。
import { reactive, toRaw } from 'vue'
const state = reactive({ count: 0 })
const raw = toRaw(state)
console.log(raw.count)
10. isRef / isReactive
- 判断是否为响应式数据。
import { ref, reactive, isRef, isReactive } from 'vue'
console.log(isRef(ref(1))) // true
console.log(isReactive(reactive({}))) // true
console.log(isRef({})) // false
注意点
- 解构 reactive 时用
toRefs,否则响应断链。 ref访问和修改必须.value。reactive不能直接替换整体对象。- 浅响应式只响应第一层。
总结
ref:基本数据响应。reactive:对象响应。computed:缓存计算。toRefs:安全解构。readonly:只读保护。shallowReactive/shallowRef:浅层响应。customRef:自定义响应逻辑。toRaw:获取原始对象。isRef/isReactive:检测响应类型。