toRaw和markRaw

toRaw

  • 响应式数据拆解,当通过ref或者reactive生成响应式数据的时候,修改数据不想引起UI的变化
    举个栗子如下
<template>
  <div class="page-wrapper">
    <p>-------------------------------toRaw-----------------------</p>
    <p>stu: {{stu}}</p>
    <button @click="changeStu">点我一下,changeStu</button>
    <p>rawStu: {{rawStu}}</p>
    <button @click="changeRawStu">>点我一下,changeRawStu</button>
  </div>
</template>
<script lang="js">
import { defineComponent, reactive, toRaw } from 'vue';
export default defineComponent({
  name: 'toRow-test',
  setup(){
    let stu= reactive({
        name: 'zs',
        age: 18
    })
    let rawStu= toRaw(stu);
    function changeStu() {
        stu.name= 'ls';

    }
    function changeRawStu() {
        rawStu.name= 'ww';
        console.log('changeStu', stu);
        console.log('changeRawStu', rawStu);
    }
    return {
        stu,
        rawStu,
        changeStu,
        changeRawStu
    }
  }
  
})
</script>

markRaw

  • 原始数据通过markRaw封装之后,再用ref或者reactive封装的时候返回的还是原始数据
    还是举个栗子
<template>
  <div class="page-wrapper">
    <p>-------------------------------markRow-----------------------</p>
    <p>stu: {{stu}}</p>
    <button @click="changeStu">点我一下,changeStu</button>
  </div>
</template>
<script lang="js">
import { defineComponent, reactive, markRaw } from 'vue';
export default defineComponent({
  name: 'toRow-test',
  setup(){
    let obj= {
        name: 'zs',
        age: 18
    }
    obj= markRaw(obj);
    console.log('markRaw obj', obj);
    let stu= reactive(obj);
    console.log('reactive stu', stu);
    function changeStu() {
        stu.name= 'ls';
        console.log('changeStu', stu);

    }
    return {
        stu,
        changeStu
    }
  }
  
})
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容