readonly 和 shallowReadonly

  • readonly: 让一个响应式数据变为只读的(深只读)。

  • shallowReadonly:让一个响应式数据变为只读的(浅只读)。

  • 应用场景: 不希望数据被修改时。

<template>
    <div>
    <h1>readonly : </h1>
    姓名 : {{name}} <br> 
    薪资 : {{j.b.money}} <br>

    <button @click ='name+=1'>姓名+1</button>  <br>
    <button @click ='j.b.money++'>薪资+1</button>

    <hr>
    <hr>
    <h1>shallowReadonly</h1>
    姓名 : {{name1}} <br> 
    薪资 : {{j1.b.money}} <br>

    <!-- 只读 -->
    <button @click ='name1+=1'>姓名+1</button>  <br>
    <!-- 可以得到 -->
    <button @click ='j1.b.money++'>薪资+1</button>  
    </div>
</template>

<script>
    import { reactive,toRefs ,readonly,shallowReadonly}    from 'vue'
    export default {
        name: 'App',
        setup() {
      //  readonly 深层次只读 ---reactive和ref都有效
      let data = readonly(reactive({
        name:'吴宇腾',
        j:{
          b:{
            money:18
          }
        }
      }))

      // shallowReadonly 浅层次[只有第一次] ---reactive和ref都有效
      let data1 = shallowReadonly(reactive({
        name1:'吴宇腾1',
        j1:{
          b:{
            money:11
          }
        }
      }))

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

 

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