VUE Framework Vue3 The difference between deep read-only and shallow read-only and specific application scenarios------VUE Framework

<template>
    <h1>{
    
    { data.counter }}</h1>
    <br>
    <h1>{
    
    { data.a.b.counter2 }}</h1>
    <button @click="data.counter++">counter+1</button>
    <button @click="data.a.b.counter2++">counter2+1</button>
</template>

<script>
import { reactive, readonly, shallowReadonly } from 'vue'
export default {
    name : "App",
    setup(){
        let data = reactive({
            counter : 1,
            a : {
                b : {
                    counter2 : 100
                }
            }
        });
        // 深只读(具有响应式的对象的所有属性均不可修改,包括对象的子对象在内的属性,都不可修改)
        // data = readonly(data);
        // 浅只读(具有响应式的对象的第一层属性是只读的,更深的属性和子对象属性可以修改)
        // 只读用在其他组件和当前组件共享响应式数据的时候
        // 不希望这个数据被我们当前的组件修改,就使用只读修饰
        // 因为那个数据在别的组件用的,只是给我们这个组件可能是显示一下罢了
        data = shallowReadonly(data);
        // 返回对象
        return {data};
    }
}
</script>

<style>

</style>

<template>

    <h1>{ { data.counter }}</h1>

    <br>

    <h1>{ { data.a.b.counter2 }}</h1>

    <button @click="data.counter++">counter+1</button>

    <button @click="data.a.b.counter2++">counter2+1</button>

</template>

<script>

import { reactive, readonly, shallowReadonly } from 'vue'

export default {

    name : "App",

    setup(){

        let data = reactive({

            counter : 1,

            a : {

                b : {

                    counter2 : 100

                }

            }

        });

        // Deep read-only (all properties of the responsive object cannot be modified, including the properties of the object's sub-objects, cannot be modified)

        // data = readonly(data);

        // Shallow read-only (the first-level properties of responsive objects are read-only, deeper properties and sub-object properties can be modified)

        // Read-only is used when other components share responsive data with the current component

        // If we don’t want this data to be modified by our current component, use read-only modification.

        // Because that data is used in other components, it is just for display in this component.

        data = shallowReadonly(data);

        //return object

        return {data};

    }

}

</script>

<style>

</style>

import mitt from 'mitt';
// 这个会创建一个对象emitter
// 把它当作全局事件总线对象即可
export default mitt();

import my from 'my';

// This will create an object emitter

// Just treat it as a global event bus object

export default mitt();

Guess you like

Origin blog.csdn.net/2201_75960169/article/details/135246001