vue3 的两种变量ref&reactive
- 使用 ref 定义基本数据类型的响应式变量, 使用reactive 定义数组或对象类型的响应式变量, 都是响应的
const count = ref(0)
const obj = reactive({ count: 0 })
- 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 的心智负担
推荐阅读
- 热闹中的孤独
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 布丽吉特,人生绝对的赢家
- 慢慢的美丽
- 尽力
- 一个小故事,我的思考。
- 家乡的那条小河
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量