← 返回首页
Vue3基础教程(二十八)
发表时间:2021-08-12 16:33:58
shallowReactive 与 shallowRef

shallowReactive : 只处理了对象内最外层属性的响应式(也就是浅响应式) shallowRef: 只处理了value的响应式, 不进行对象的reactive处理

什么时候用浅响应式呢?

实例:

<template>
    <h2>App</h2>
    <h3>m1: {{m1}}</h3>
    <h3>m2: {{m2}}</h3>
    <h3>m3: {{m3}}</h3>
    <h3>m4: {{m4}}</h3>
    <button @click="update">更新</button>
</template>

<script lang="ts">
    import {reactive, ref, shallowReactive, shallowRef} from 'vue'
    export default {
        setup() {
            const m1 = reactive({name: 'zhangsan', age: 20, car: {brand: 'BMW'}})
            const m2 = shallowReactive({name: 'lisi', age: 20, car: {brand: 'BMW'}})
            const m3 = ref({name: 'wangwu', age: 20, car: {brand: 'BMW'}})
            const m4 = shallowRef({name: 'zhaoliu', age: 20, car: {brand: 'BMW'}})
            const update = () => {
                //m1.name = 'jerry';
                //m1.car.brand = 'BENZ';
                //m2.name = 'jerry';
                m2.car.brand = 'FORD';
                /*
                m3.value.name = 'jerry';
                m3.value.car.brand = 'BENZ';
                */
                m4.value.name = 'jerry';
                m4.value.car.brand = 'TOYOTA';
                console.log(m1,m2,m3,m4);
            }
            return {
                m1,
                m2,
                m3,
                m4,
                update,
            }
        }
    }
</script>