本文章主要为大家介绍了Vue3中shallowRef和shallowReactive函数的使用方法,文中的示例代码讲解详细,对我们学习Vue有一定的帮助,需要的可以参考一下
shallowReactive
只能实现复杂数据类型的第一层响应式。
<template> <!-- shallowReactive --> <div>{{ obj }}</div> <button @click="obj.children.age++">修改children.age</button> </template> <script> import { reactive, shallowReactive} from "@vue/reactivity"; export default { setup() { //使用shallowReactive只能对复杂数据类型的第一层数据实现响应式 //既name,age,无法对children下的name,age实现响应式 let obj = shallowReactive({ name: "张三", age: 18, children: { name: "张三三", age: 2, }, }); return { obj, }; }, }; </script> <style></style>
shallowRef
只能对简单数据类型实现响应式,如果是复杂数据类型,则无法实现响应式
<template> <!-- shallowRef --> <div>{{ counter.x }}</div> <button @click="counter.x++">counter.x++</button> </template> <script> import { shallowRef } from "@vue/reactivity"; export default { setup() { //shallowRef 只能对简单数据类型实现响应式 //无法对复杂数据类型实现响应式 let counter = shallowRef({ x: 0, }); return { counter, }; }, }; </script> <style></style>