其他分享
首页 > 其他分享> > toRaw和markRaw

toRaw和markRaw

作者:互联网

 

<template>
    <div>
    <h1>toRaw : 响应对象变为普通对象 </h1>
    姓名 : {{name}} <br> 
    薪资 : {{a.b.money}} <br>
    车信息 : {{data.cart}}  <br>

    <button @click ='changName'>姓名+1</button>  <br>
    <button @click ='changMoney'>薪资+1</button> <br>

    <button @click="changetoRaw">点击toRaw(响应对象变为普通对象)</button>  <br>
    <button @click="changeCar">点击添加车</button> <br>
    <button @click="cartPrice">改变cart的价格</button>
    

    <hr>
    <hr>
    <h1>标记一个对象,使其永远不会再成为响应式对象</h1>
    <button @click="cartMarkRaw">把cart永远不能变成响应式的</button>
 
    </div>
</template>

<script>
    import { reactive,toRefs ,toRaw,markRaw}    from 'vue'
    export default {
        name: 'App',
        setup() {
      let data = reactive({
        name:'吴宇腾',
        a:{
          b:{
            money:15
          }
        }
      })
      let changName = ()=>{
        data.name+=1
        console.log('changName'+JSON.stringify(data))
      }
      let changMoney = ()=>{
        data.a.b.money +=1
        console.log('changMoney'+JSON.stringify(data))
      }
      // 点击 : 响应对象变为普通对象
      let changetoRaw = ()=>{
        console.log('changetoRaw'+JSON.stringify(data))
        data = toRaw(data)
        console.log('changetoRaw'+JSON.stringify(data))
      }

      let cart = {
          name:'x5',
          price : 18
      }

      // 点击添加车
      let changeCar = ()=>{       
        
        data.cart = cart
        console.log('点击添加车',JSON.stringify(data),data)
      }

      // 改变cart的价格
      let cartPrice = ()=>{
        data.cart.price+=1
        console.log('改变cart的价格',JSON.stringify(data))
      }

      // 把cart永远不能变成响应式的 => 就算你再点击为响应式的,也变不回去了
      let cartMarkRaw = ()=>{
        data.cart = markRaw(cart)
        console.log('把cart永远不能变成响应式的',JSON.stringify(data),data.cart)
      }

      return{
        data,
        ...toRefs(data),
        changName,
        changMoney,
        changetoRaw,
        changeCar,
        cartPrice,
        cartMarkRaw
      }
        }
    }
</script>

 

标签:stringify,对象,cart,响应,toRaw,let,markRaw,data
来源: https://www.cnblogs.com/qd-lbxx/p/16292565.html