vue3.0中的readonly和shallowReadonly

readonly:将包裹的对象变为只读,并且是深度只读

<template>
  <div>
    <h2>readonly与shallowReadonly</h2>
    <h3>state:{{state}}</h3>
    <button @click="update">更新数据</button>
  </div>
</template>


<script lang="ts">
import { computed, defineComponent,onMounted,reactive,readonly,ref, } from 'vue'
export default defineComponent({
    setup(){
      const state = reactive({
        name:'小明',
        age:12,
        car:{
          name:'奔驰',
          color:'red'
        }
      })
      const state2 = readonly(state)
      const update = () => {
        state2.name += '---'
      }
      
      return {
        state,state2,
        update
      }
    }
})
</script>

效果如下图:
可以看到报错了,state2中的name属性是一个只读属性
vue3.0中的readonly和shallowReadonly_第1张图片
修改代码:

const update = () => {
  state2.car.name += '---'
}

效果如下图:
可以看到,state2中的car的name属性是一个只读属性
vue3.0中的readonly和shallowReadonly_第2张图片
shallowReadonly:浅层属性为只读,深层次属性可以修改

浅层次代码:

const state2 = shallowReadonly(state)
	const update = () => {
	  state2.name += '---'
	  console.log('测试')
}

效果图:
vue3.0中的readonly和shallowReadonly_第3张图片
深层次代码:

const update = () => {
	 state2.car.name += '---'
	 console.log('测试')
}

点击按钮,效果图:
可以看到深层次属性值发生了变化
vue3.0中的readonly和shallowReadonly_第4张图片

总结:
(1)readonly:将包裹的对象变为只读,并且是深度只读
(2)shallowReadonly:浅层属性为只读,深层次属性可以修改

你可能感兴趣的:(javascript,vue.js,前端)