vue3中 ref和reactive使用上的区别
时间:2021-02-16 12:17:09
收藏:0
阅读:0
ref和reactive使用上的区别(vue3 组合式api中)
在vue3中对响应式数据的声明官方给出了
ref()
和reactive()
这两种方式
响应式数据:是指当数据改变后,Vue 会通知到使用该数据的代码。例如,视图渲染中使用了数据,数据改变后,视图也会自动更新。
定义数据
reactive
:参数必须是对象(json
/arr
)
# ref
const count = ref(0)
# reactive
const obj = reactive({ count: 0 })
修改数据
ref
:必须加上.value
。
reactive
:不能改变对象本身,但可以改变内部count
的值。(即使使用let
定义,虽然不会报错但是页面不会有响应)
# ref
count.value = 2
# reactive
obj.count = 2
return
和template中使用时,以及toRefs
的使用
注意:使用
toRefs
时,obj
里面的count
与上面ref
的count
名称重复了,实际使用时改个名称
ref
:在template中
ref
不需要加.value
# return时 return { count } # template <el-button type="primary" @click="count++" size="mini">count is: {{ count }}</el-button>
reactive
:return { obj } # template <el-button type="primary" @click="obj.count++" size="mini">count is: {{ obj.count }}</el-button>
“...”的意思,这里相当于
return { count: toRefs(obj).count }
return { ...toRefs(obj) } # template <el-button type="primary" @click="count++" size="mini">count is: {{ count }}</el-button>
参考文章
https://www.yuque.com/yanmou-pupa9/hkbhdx/tvrwtl
https://zhuanlan.zhihu.com/p/268053724
https://www.jianshu.com/p/43828470de79
https://www.cnblogs.com/jinzhenzong/p/12778729.html
评论(0)