vue3 | shallowReactive 、shallowRef、triggerRef

shallowReactive

使用reactive声明的变量为递归监听,使用shallowReactive声明的变量为非递归监听(通俗的讲就是reactive创建的对象将会被vue内部进行递归监听,可以监听到对象中的对象是否发生了改变从而更新视图,而shallowReactive创建的对象只能监听到首层对象的变化)。

<script setup lang="ts">
  import { shallowReactive } from 'vue'
  const state = shallowReactive({
    a: 1,
    b: {
      res: 2,
      c: {
        res: 3,
      },
    },
  })
  
  const handleCLick = () => {
    state.a = 100
    state.b.res = 200
    state.b.c.res = 300
  }
</script>
<template>
  <n-el class="flex flex-col justify-center items-center w-full h-200">
    <n-el>{{ state.a }}</n-el>
    <n-el>{{ state.b.res }}</n-el>
    <n-el>{{ state.b.c.res }}</n-el>
    <n-button @click="handleCLick" class="!w-20">点击</n-button>
  </n-el>
</template>

动画.gif

shallowRef

其中shallowRef为非递归监听,ref为递归监听,与shallowReactive和reactive不同的是shallowRef和ref监听的对象首层是value这一层,只有当value发生改变时shallowRef声明的变量才会在视图上进行更新。
shallowRef只有对 .value 的访问是响应式的。

<n-el>{{ state2.res }}</n-el>
<n-button class="!w-20" @click="handleCLick">点击</n-button>

......
 const handleCLick = () => {
    // state2.value.res = 9999 //不会触发
  }

动画.gif

  const handleCLick = () => {
     state2.value = {  //会触发
       res: 9999,
     }
  }

动画.gif

    <n-el>{{ state2.res }}</n-el>
    <n-el>{{ state2.res2.data }}</n-el>
    <n-el>{{ state2.res2.res3.data }}</n-el>
    <n-button class="!w-20" @click="handleCLick">点击</n-button>

......
  const handleCLick = () => {
    state2.value = {
      res: 100,
      res2: {
        data: 200,
        res3: {
          data: 300,
        },
      },
    }
  }

动画.gif

triggerRef

triggerRef的作用则是手动执行与 shallowRef 关联的任何副作用,强制更新视图。

  const handleCLick = () => {
    state.value.a = 100
    state.value.b.res = 200
    state.value.b.c.res = 300
    state2.value.res = 9999 
    triggerRef(state2)
  }
  
  
  ......
   <n-el>{{ state2.res }}</n-el>
   <n-el>{{ state2.res2.data }}</n-el>
   <n-el>{{ state2.res2.res3.data }}</n-el>
   <n-button class="!w-20" @click="handleCLick">点击</n-button>

动画.gif

参考文档:

1、https://www.jianshu.com/p/4e0d4fcff950

2、https://blog.csdn.net/zxBlogs/article/details/114546382

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值