【vue3】ref、reactive、shallowRef、shallowReactive、readonly和shallowReadonly

申明变量的几种方法

  • 一般情况下使用 ref 和 reactive 即可
  • 如果有一个对象数据,结构比较深,但变化只是外层属性变化 ===> shallowReactive
  • 如果有一个对象数据,后面会产生新的对象来替换 ===> shallowRef
  • 深度只读数据 ===> readonly
  • 浅度只读数据 ===> shallowReadonly
<template>
    <h3>m1:{{m1}}</h3>
    <h3>m2:{{m2}}</h3>
    <h3>m3:{{m3}}</h3>
    <h3>m4:{{m4}}</h3>
    <h3>m5:{{m5}}</h3>
    <h3>m6:{{m6}}</h3>
    <button @click="update">更新数据</button>
</template>

<script lang="ts">
import { ref,reactive,shallowRef,shallowReactive,readonly,shallowReadonly } from 'vue'
export default {
    setup(props) {
        const m1 = ref({
            name:'小明',
            family:{
                father:'大明'
            }
        })
        const m2 = reactive({
            name:'小明',
            family:{
                father:'大明'
            }
        })
        const m3 = shallowRef({
            name:'小明',
            family:{
                father:'大明'
            }
        })
        const m4 = shallowReactive({
            name:'小明',
            family:{
                father:'大明'
            }
        })
        const m = reactive({
            name:'小明',
            family:{
                father:'大明'
            }
        })
        const m5 = readonly(m)
        const m6 = shallowReadonly(m)
        /**
         * 一般情况下使用 ref 和 reactive 即可
         * 如果有一个对象数据,结构比较深,但变化只是外层属性变化 ===> shallowReactive
         * 如果有一个对象数据,后面会产生新的对象来替换 ===> shallowRef
         * 深度只读数据 ===> readonly
         * 浅度只读数据 ===> shallowReadonly
         */
        const update = () => {
            // m1.value.family.father = '111'
            // m2.family.father = '222'
            // m3.value.name = '333' 和 m3.value.family.father 不生效
            // m4.name = '444'
            // m4.family.father = '444' 不生效
            // m5.name = '555' 和 m5.family.father = '555'报错
            // m6.name = '666' 报错
            m6.family.father = '666'
        }
        return{
            m1,
            m2,
            m3,
            m4,
            m5,
            m6,
            update
        }
    }
}
</script>

你可能感兴趣的:(vue3,vue.js,javascript,前端)