vue3学习——Reactive全家桶

reactive

返回对象的响应式副本,响应式转换是“深层”的——它影响所有嵌套 property。

ref一般用来绑定简单数据类型,

reactive源码中限制了绑定的数据类型,只能绑定复杂数据类型( Object ,Array ),否则会报错

引入

import { reactive } from "vue"

定义变量

数组:

let arr = reactive([])
//或者
type O = Number[]
let arr = reactive([])

对象 :

let obj = reactive({
    name:"皮皮鲁",
    info:{
        sex:"male"
        }
    })

修改

//视图1
{{ item }}
//视图2
{{ item }}
//视图3
{{obj.name}}
//视图4
{{obj.info.sex}}

数组: 

arr = [1,2,3] //视图1 不更新  重新赋值破坏了原响应式

//方法1:解构赋值
arr.push(...[1,2,3]) //视图1更新

//方法2: 通过一个对象绑定arr
type O={
    arr:number[]
}
let arrObj = reactive({
    arr:[]
}

arrObj.arr=[1,2,3] //视图2更新

对象:

obj.name = "鲁西西"  //视图3更新

onj.info.sex = "female" //视图4更新


 注:reactive 将解包所有深层的 refs,同时维持 ref 的响应性。

即 

const testR = () => {
  let a = ref(1)
  let b = reactive({ a })
  let c = reactive({
    a: 1
  })
  console.log('[ b.a ] >', b.a)
  console.log('[ c.a ] >', c.a)
  console.log('[ a.value ] >', a.value)
}
testR()

//输出
//[ b.a ] > 1
//[ c.a ] > 1
//[ a.value ] > 1

readonly

接受一个对象 (响应式或纯对象) 或 ref 并返回原始对象的只读代理。只读代理是深层的:任何被访问的嵌套 property 也是只读的。

let obj = reactive({ a : 1 })
let copy = readonly(obj)

console.log(copy.a) //1
copy.a++  //警告

shallowReactive

创建一个响应式代理,它跟踪其自身 property 的响应性,但不执行嵌套对象的深层响应式转换 (类似于shallowRef)。

引入

import { shallowReactive } from "vue"

定义变量

let obj = shallowReactive({
    name:"皮皮鲁",
    info:{
        sex:"male"
        }
    })

修改

//视图1
{{obj.name}}
//视图2
{{obj.info.sex}}
const change1=()=>{
obj.name="鲁西西"
}

const change2=()=>{
obj.info.sex="female" 
}

const change3=()=>{
obj.info.sex="female" 
obj.name="鲁西西"
}

change1()   //视图1更新
change2()   //视图2不更新
change3()   //视图 1 2 更新

注 :自身响应性property改动会触发嵌套对象的视图更新,挂载之前的数据操作也会在视图生效

shallowReadonly

readonly() 的浅层作用形式

和 readonly() 不同,这里没有深层级的转换:只有根层级的属性变为了只读。属性的值都会被原样存储和暴露,这也意味着值为 ref 的属性 不会被自动解包了。

你可能感兴趣的:(学习,前端,vue)