readonly

  • 使用 readonly 函数包装过的对象,内部是深层次只读的

shallowReadonly

  • 使用 shallowReadonly 函数包装过的对象,只有最外层属性是只读的,内层仍然可以改写

示例:

<template>
  <button @click="change">改变</button>
</template>

<script lang="ts">

import { defineComponent, readonly, shallowReadonly} from 'vue';

export default defineComponent({
  name: 'Child',

  setup() {
    let data1 = readonly({
      name: 'a'
      deep: {
        name: 'b'
      }
    })
    let data2 = shallowReadonly({
      name: 'a',
      deep: {
        name: 'b'
      }
    })

    let change = ()=>{
      data1.name = 'aa' // 出错
      data1.deep.name = 'bb' // 出错
      data2.name = 'aa' // 出错
      data2.deep.name = 'bb' // 正常
    }

    return {
      change
    }
  }
});
</script>