vue3 | readonly、shallowReadonly

文章通过代码示例展示了在Vue中如何使用readonly和shallowReadonly函数创建对象的只读代理。readonly用于创建一个对象的深层只读版本,而shallowReadonly则创建浅层的只读对象,只保护顶级属性不被修改。文章通过添加数据到原始和只读对象来演示它们的区别,强调了对响应式数据的修改控制。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值