Reasons why using shallowRef in vue3 will still trigger changes

About shallowRef()

ref()superficial form of action.

  • details

Unlike ref(), the internal value of a shallow ref will be stored and exposed as-is, and will not be recursively converted to reactivity by a deep layer. Only access to .value is reactive.

shallowRef() is often used for performance optimization of large data structures or integration with external state management systems.

  • example
const state = shallowRef({
    
     count: 1 })

// 不会触发更改
state.value.count = 2

// 会触发更改
state.value = {
    
     count: 2 }

But when I am using it, state.value.countthe modified view is still updated.
code show as below:

<script setup>
import { ref, shallowRef, triggerRef } from 'vue'

// shallowRef
// 和 ref() 不同,浅层 ref 的内部值将会原样存储和暴露,并且不会被深层递归地转为响应式。
const state = shallowRef({ count: 1 })
const state1 = ref({ count: 1 })
console.log(state.value) // 变为正常对象,失去响应式
console.log(state1.value) // proxy响应式对象
function add() {
  state.value.count++
  // state1.value.count++
  console.log(state.value)
  console.log(state1.value)
}
</script>

<template>
  <h1>state:{
   
   { state }}</h1>
  <h1>state1:{
   
   { state1 }}</h1>
  <button @click="add">++</button>
</template>

<style></style>

insert image description here

reason:

Because when state1 changes, the responsive update of ref is triggered.
Looking at the source code, we found that, as shown in the figure below: insert image description here
The update of ref is called triggerRefValue(this, newVal), which triggers the view update. At this time, state and state1 are in a function scope, so the state will also be triggered to update.
But this kind of trigger update is imprecise.
The official recommendation is to use it to actively trigger update after modifying the deep data defined by shallowRef triggerRef(), rather than through this non-standard method.
insert image description here

Guess you like

Origin blog.csdn.net/weixin_42566993/article/details/129679141