其他分享
首页 > 其他分享> > vue3 组合api的简单使用

vue3 组合api的简单使用

作者:互联网

 

//compostion api (组合api)
import { ref, reactive,onBeforeMount, onMounted,onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted,computed } from 'vue'
export default{
    setup(){
        // 非响应式变量
        let msg = "hello wrold";
        // 响应式变量
        let title = ref("hello wrold");
        const student = reactive({ name: "小米", age: 18 });
        function sayHi(){
            msg = "hello vue";  //msg的值不会变
            title.value = "hello vue";
            student.name = "小明";
        }
        
        // 生命周期
        //setup本身就是created
        console.log('beforeCreate')
        onBeforeMount(()=>{
            console.log("onBeforeMount")
        })
        onMounted(()=>{})
        onBeforeUpdate(()=>{})
        onUpdated(()=>{})
        onBeforeUnmount(()=>{})
        onUnmounted(()=>{})
        
        // 计算属性
        const number = computed(()=>{
            return 100
        })
        
        // 暴露出变量以及方法
        return { msg, title, student, sayHi, number }
        
    }
}

 

//对比vue2的选项api

export default{
    data(){
        return {
            msg: 'hello world',
            total: 0
        }
    },
    //计算属性
    computed:{
        total(){
            return 100
        }    
    },
    // 生命周期
    beforeCreate:{},
    created{},
    beforeMount{},
    mounted{},
    // ...
    methods:{
        showHi(){}    
    }
}

 

标签:return,computed,组合,onBeforeMount,api,vue3,msg,hello
来源: https://www.cnblogs.com/ruyijiang/p/15959825.html