Vue3.0API介绍中 shallowReactive 使用示例

Vue3.0API介绍中 shallowReactive 使用示例
Vue3.0API介绍中 shallowReactive 使用示例
 
 
shallowReactive
创建一个响应式代理,它跟踪其自身 property 的响应性,但不执行嵌套对象的深层响应式转换 (暴露原始值)。
 
<script setup>
import { shallowReactive, isReactive } from "vue";
 
const state = shallowReactive({
  foo: 1,
  nested: {
    bar: 2
  }
})
 
// 改变 state 本身的性质是响应式的
state.foo++
// ...但是不转换嵌套对象
console.log(isReactive(state.nested)) // false
state.nested.bar++ // 非响应式
</script>
与 reactive 不同,任何使用 ref 的 property 都不会被代理自动解包。
 
shallowReadonly
创建一个 proxy,使其自身的 property 为只读,但不执行嵌套对象的深度只读转换 (暴露原始值)。
 
<script setup>
import { shallowReadonly, isReadonly } from "vue";
 
const state = shallowReadonly({
  foo: 1,
  nested: {
    bar: 2
  }
})
 
// 改变 state 本身的 property 将失败
state.foo++
console.log(isReadonly(state))
// ...但适用于嵌套对象
console.log(isReadonly(state.nested)) // false
state.nested.bar++ // 适用
</script>
 
 
与 readonly 不同,任何使用 ref 的 property 都不会被代理自动解包。

推荐阅读