美文网首页
Vue3响应式 API:进阶(学习笔记)

Vue3响应式 API:进阶(学习笔记)

作者: kevision | 来源:发表于2022-08-18 17:53 被阅读0次

shallowRef()


ref() 的浅层作用形式。

示例
import { shallowRef, watchEffect } from 'vue'
// 浅层ref不会递归转换为响应式,只有到.value层是响应式的
const state = shallowRef({count: 1})
watchEffect(() => {
    console.log("state", state.value.count)
})
// 1
state.value.count = 2 // 不会触发更新
// 2
state.value = {count: 2} // 会触发更新

triggerRef()


强制触发依赖于一个浅层 ref 的副作用,这通常在对浅引用的内部值进行深度变更后使用。

示例
import { shallowRef, triggerRef, watchEffect } from 'vue'
const state = shallowRef({count: 1})
watchEffect(() => {
    console.log("state", state.value.count)
})
state.value.count = 2 // 不会触发更新
triggerRef(state) // 强制触发浅层ref-->触发更新

shallowReactive()


reactive() 的浅层作用形式。

详细信息
和 reactive() 不同,这里没有深层级的转换:一个浅层响应式对象里只有根级别的属性是响应式的。属性的值会被原样存储和暴露,这也意味着值为 ref 的属性 不会被自动解包了。

示例
const state = shallowReactive({
  foo: 1,
  nested: {
    bar: 2
  }
})

// 更改状态自身的属性是响应式的
state.foo++

// ...但下层嵌套对象不会被转为响应式
isReactive(state.nested) // false

// 不是响应式的
state.nested.bar++

shallowReadonly()


readonly() 的浅层作用形式

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

示例
const state = shallowReadonly({
  foo: 1,
  nested: {
    bar: 2
  }
})

// 更改状态自身的属性会失败
state.foo++

// ...但可以更改下层嵌套对象
isReadonly(state.nested) // false

// 这是可以通过的
state.nested.bar++

相关文章

网友评论

      本文标题:Vue3响应式 API:进阶(学习笔记)

      本文链接:https://www.haomeiwen.com/subject/nipxgrtx.html