ref和reactive的区别

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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值