shallowReactive 和 shallowRef

  • shallowReactive:只处理对象最外层属性的响应式(浅响应式)。

  • shallowRef:只处理基本数据类型的响应式, 不进行对象的响应式处理。

  • 什么时候使用?

    • 如果有一个对象数据,结构比较深, 但变化时只是外层属性变化 ===> shallowReactive。

    • 如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换 ===> shallowRef。

 

  reactive  和  shallowReactive的区别 : 

<template>
    <div>
    <h1>正常的 : reactive</h1>
    姓名 : {{name}}  <br>
    价格 : {{a.b.money}}  <br>

    <button @click =' name+= 1'>姓名+1</button>   <br>
    <button @click = a.b.money++>价格+1</button>

    <hr>
    
    <!-- 就是第一层,才具备响应式 -->
    <h1>正常的 : shallowReactive</h1>
    姓名 : {{name2}}  <br>
    价格 : {{a.b.money2}}  <br>

    <!-- 浅层次就可以 -->
    <button @click =' name2+= 2'>姓名+2</button>   <br> 
    <!-- 深层次就不行了 -->
    <button @click =' a.b.money2+=2'>价格+2</button>   

    </div>
</template>

<script>
    import {reactive,toRefs,shallowReactive,}    from 'vue'
    export default {
        name: 'App',
        setup() {
      
      // 正常的reactive
      let data = reactive({
        name:'吴宇腾',
        a:{
          b:{
            money : 18
          }
        }
      })
      // 这个是proxy
      console.log('正常的reactive的深层次: ',data.a)


      // 浅层次的shallowReactive[ 就是第一层,才具备响应式]
      let data2 = shallowReactive({
        name2:'吴宇腾2',
        a:{
          b:{
            money2 : 22
          }
        }
      })
      // 这个是obj
      console.log('shallowReactive的浅层次: ',data2.a)

      return{
        ...toRefs(data),
        ...toRefs(data2)
      }
        }
    }
</script>

 

ref 和 shallowRef 的区别 :

<template>
    <div>
    普通的ref : {{num}}  <br>
    <button @click="num++">ref++</button>
    <hr>
    shallowRef : {{shallowNum}} <br>
    <button @click="shallowNum++">shallowRef++</button>
    <hr>
    <h1>对象式的 : </h1>
    <hr>
    普通的ref对象式 : {{num1.a}}  <br>
    <button @click="num1.a++">ref++</button>
    <hr>
    shallowRef对象式 : {{shallowNum1.a}} <br>
    <button @click="shallowNum1.a++">shallowRef++</button>   


    </div>
</template>

<script>
    import {ref,toRefs,shallowRef,}    from 'vue'
    export default {
        name: 'App',
        setup() {     
      let num = ref(0)
      let shallowNum = shallowRef(0)

      // 不是对象的shallowRef 和 ref  没啥区别 ;  对象的才有区别
      let num1 = ref({
        a:1
      })      
      console.log(num1.value)// 这个是proxy

      let shallowNum1 = shallowRef({
        a:1
      })     
      console.log(shallowNum1.value)// 这个就是对象

      return{
        num,
        shallowNum,
        num1,
        shallowNum1
      }
        }
    }
</script>

 

posted @ 2022-05-20 14:08  杨建鑫  阅读(555)  评论(0编辑  收藏  举报