Reactive判断API
-
-
- [1. isProxy](#1. isProxy)
- [2. isReactive](#2. isReactive)
- [3. isReadonly](#3. isReadonly)
- [4. toRaw](#4. toRaw)
- [5. shallowReactive](#5. shallowReactive)
- [6. shallowReadonly](#6. shallowReadonly)
1. isProxy
检查对象是否是由reactive或readonly创建的proxy.
javascript
复制代码
const info1 = reactive({
name:'why',
age:18
})
const info2 = readonly(reactive({
name:'why',
age:18
}))
console.log(isProxy(info1),isProxy(info2));//true true
2. isReactive
检查对象是否由reactive创建的响应式代理:
如果该代理是readonly创建的,但包裹了由reactive创建的另一个代理,它也会返回true
javascript
复制代码
const info1 = reactive({
name:'why',
age:18
})
const info2 = readonly(reactive({
name:'why',
age:18
}))
console.log(isReactive(info1),isReactive(info2));//true true
3. isReadonly
检查对象是否由readonly创建的只读代理。
javascript
复制代码
const info1 = readonly({
name:'why',
age:18
})
const info2 = readonly(reactive({
name:'why',
age:18
}))
console.log(isReadonly(info1),isReadonly(info2));//true true
4. toRaw
返回reactive或readonly代理的原始对象(不建议保留对原始对象的持久引用。谨慎使用(转成原始对象之后是要修改原始对象不推荐))
javascript
复制代码
const info1 = readonly({
name:'why',
age:18
})
const info2 = reactive({
name:'why',
age:18
})
console.log(toRaw(info1),toRaw(info2)); //{name: 'why', age: 18} {name: 'why', age: 18}
5. shallowReactive
创建一个响应式代理,它跟踪其自身property的响应性,但不执行嵌套对象深层响应式转换(深层还是原生对象)
注意点:修改后视图不刷新。修改carName的时候,不能把其他响应式数据也放到里面,不然会带着一起修改视图
javascript
复制代码
<template>
<div>
<h2>
{{ info.car.name }} //视图不更新
</h2>
<button @click="chagneCarName">修改carName</button>
</div>
</template>
const info = shallowReactive({
name:'why',
age:18,
car:{
name:'xx'
}
})
const chagneCarName = () => {
info.car.name = 'yy'
}
6. shallowReadonly
创建一个proxy,使其自身的property为只读,但不执行嵌套对象的深度只读转换(深层还是可读、可写)
javascript
复制代码
const user = shallowReadonly({
name: 'Alice',
address: {
street: '123 Main St',
city: 'Wonderland',
}
})
const changName = () => {
user.name = '456 Elm St'; // 视图不会更新
}