vue3 | readonly、shallowReadonly

readonly

接受一个对象(不管是响应式还是普通的)或者是一个ref,返回的是一个原值的只读代理。


<template>
  <n-el class="h-400 w-full flex flex-col justify-center items-center">
    <n-el>{{ data }}</n-el>
    <n-el>{{ readonlyData }}</n-el>
    <n-button @click="handleAddData">增加data</n-button>
    <n-button class="!mt-2" @click="handleAddReadonlyData">增加readonlyData</n-button>
  </n-el>
  </template>
  
  <script setup lang="ts">
  import { readonly, ref } from 'vue'
  const data = ref(100)
  const readonlyData = readonly(data)

  const handleAddData = () => {
    data.value++
  }

  const handleAddReadonlyData = () => {
    readonlyData.value++
  }
  </script>

编辑器提示

image.png

动画.gif

shallowReadonly

readonly()的浅层作用形式

<template>
 <n-el class="h-400 w-full flex flex-col justify-center items-center">
    <n-el>{{ obj.a }}</n-el>
    <n-el>{{ obj.b.res }}</n-el>
    <n-el>{{ obj.b.c.res }}</n-el>
    <n-el>------------------------</n-el>
    <n-el>{{ readonlyObj.a }}</n-el>
    <n-el>{{ readonlyObj.b.res }}</n-el>
    <n-el>{{ readonlyObj.b.c.res }}</n-el>
    <n-button class="!mt-2" @click="handleAddObj">增加obj</n-button>
    <n-button class="!mt-2" @click="handleAddReadonlyObj">增加readonlyObj</n-button>
  </n-el>
 </template>
 
  <script setup lang="ts">
  import { reactive, shallowReadonly } from 'vue'
    const obj = reactive({
    a: 1,
    b: {
      res: 2,
      c: {
        res: 3,
      },
    },
  })

  const readonlyObj = shallowReadonly(obj)

  const handleAddObj = () => {
    obj.a = 100
    obj.b.res = 200
    obj.b.c.res = 300
  }

  const handleAddReadonlyObj = () => {
    readonlyObj.a = 100
    readonlyObj.b.res = 200
    readonlyObj.b.c.res = 300
  }
</script>

image.png

增加obj

动画.gif

增加readonlyObj

动画.gif

posted @ 2023-02-07 20:17  杨芋可可  阅读(59)  评论(0编辑  收藏  举报