vue3 reacitve-ref区别

结论:用ref定义基本类型,用reactive来定义引用类型,如果用reactive定义基本类型,watch监听会不好用。

<template>
        <div>
            <!-- 页面上不需要加value -->
            {{num}} {{dept.loc}}{{dept2.loc}}<br>
            num3:{{num3}}<br>
            num3new:{{num3new}}<br>
            numnew:{{numnew}}<br>
            <button @click="add(5)">改</button>
        </div>
    </template>

    <script setup>
        import {  computed, onMounted, reactive, ref, watch } from 'vue';
        
        //1-用ref来定义响应数据-基本类型
        let num=ref(10)
         //2-用ref来定义响应数据-引用类型
        let dept=ref({
            deptno:10,
            dname:'测试部',
            loc:'沈阳'
        })
        let add=(i)=>{
            //2-js修改时需要加.value才可以。
            num.value+=i;
            //修改时也需要加.value
            dept.value.loc='大连'
            dept2.loc="深圳-reactive"
            num3++;
        }
        //reactive只能用来定义引用类型,不能定义基本类型
        //在js和页面引用时,不需要加.value
        let num3=reactive(20)
        let dept2=reactive({
            deptno:20,
            dname:'开发',
            loc:'沈阳-reactive'
        })
        let num3new=computed(()=>{
            return '$'+num3
        })
        let numnew=computed(()=>{
            return '$'+num.value
        })
        
        /* watch(num,(newv,oldv)=>{
            alert(newv)
            alert(oldv)
        }) */
        ////用reactive定义基本类型,watch会有bug
        watch(num3,(newv,oldv)=>{
            alert(newv)
            alert(oldv)
        })
        //setup语法糖方式,生命周期函数前加on 
        /* onMounted(()=>{
            alert("onMounted")
            
        }) */
    </script>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容