ref和reactive都会让组件具有响应式,对变化作出反应。
ref和reactive存在三个区别:
1.ref()
函数可以接受原始类型(最常见的是布尔值、字符串和数字)以及对象作为参数,而 reactive()
函数只能接受对象作为参数。
原始数据类型:null undefined boolean string number symbol bigint
2.ref()
有一个 .value
属性,你必须使用 .value
属性获取内容,但是使用 reactive()
的话可以直接访问。
const x = reactive({ name: 'John'})
x.name = 'Amy'
// x => { name: 'Ammy' }
const x = ref({ name: 'John'})
x.value.name = 'Amy'
// x.value => { name: 'Ammy' }
注意:ref
传递到模板(<template>
)时,会被解包,因此你不需要在那里写 .value
。
3.使用 ref()
函数可以替换整个对象实例,但是在使用 reactive()
函数时就不行。
// 无效 - x 的更改不会被 Vue 记录
let x = reactive({name: 'John'})
x = reactive({todo: true})
// 有效
const x = ref({name: 'John'})
x.value = {todo: true}
ref()
在背后就是使用的 reactive()
,你可以把 ref()
简单看成:
const myRef = reactive({
value: "I'm ref!"
})
myRef.value // "I'm ref!"
myRef.value = 'Changed'
myRef.value // "Changed"