vue3 的两种变量ref&reactive

  1. 使用 ref 定义基本数据类型的响应式变量, 使用reactive 定义数组或对象类型的响应式变量, 都是响应的
const count = ref(0) const obj = reactive({ count: 0 })

  1. vue3使用reactive包裹数组和对象不能直接赋值, 否则会失去响应性。
    要用「响应式值引用」, 不用普通的基本类型值与对象,否则容易失去响应性
如 const arry1 = reactive([1]) 在js 中直接赋值,将失去响应性: arry1 = [1,2,3]//arry1=[1] 可以这么定义 const data = https://www.it610.com/article/reactive({arry1:[1]}) 在js 中使用 data.arry1 = [1,2,3] // arry1=[1,2,3]

2.创建的响应式变量, 不能进行解构或展开, 否则变量将失去响应效果, 可以使用 toRefs API
如 const book = reactive({ author: 'Vue Team', year: '2020', title: 'Vue 3 Guide' })let { author, title } = toRefs(book)title.value = 'https://www.it610.com/article/Vue 3 Detailed Guide' // 我们需要使用 .value 作为标题,现在是 ref console.log(book.title) // 'Vue 3 Detailed Guide' 而不能这么解构 let { author, title } = book 也不能使用展开: ...book

【vue3 的两种变量ref&reactive】总结一下,一共有两种变量风格:
就像你在普通 JavaScript 中区别声明基础类型变量与对象变量时一样区别使用 ref 和 reactive。所有的地方都用 reactive,然后记得在组合函数返回响应式对象时使用 toRefs。这降低了一些关于 ref 的心智负担

    推荐阅读