来源:vue.js官方文档 cn.vuejs.org/guide/essen…
1、响应式对象其实是 JavaScript Proxy,其行为表现与一般对象相似。
import { reactive } from 'vue'
const state = reactive({ count: 0 })
2、reactive() API 有两条限制:
a、仅对对象类型有效(对象、数组和 Map、Set 这样的集合类型),而对 string、number 和 boolean 这样的 原始类型 无效。
b、因为 Vue 的响应式系统是通过属性访问进行追踪的,因此我们必须始终保持对该响应式对象的相同引用。这意味着我们不可以随意地“替换”一个响应式对象,因为这将导致对初始引用的响应性连接丢失。
3、基于reactive的限制,Vue 提供了一个 ref() 方法来允许我们创建可以使用任何值类型的响应式 ref。
ref() 将传入参数的值包装为一个带 .value 属性的 ref 对象
const count = ref(0)
console.log(count) // { value: 0 }
console.log(count.value) // 0
count.value++
console.log(count.value) // 1
4、当 ref 在模板中作为顶层属性被访问时,它们会被自动“解包”,所以不需要使用 .value。
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
<button @click="increment">
{{ count }} <!-- 无需 .value -->
</button>