Vue中的选项式API(Options API)与函数式编程(Composition API)方式

Vue中的选项式API(Options API)

介绍

Vue2(虽然Vue3也支持)采用选项式API(Options API)格式,该格式会导致对相同数据进行操作使用的代码被分割到不同属性内,很不利于代码的阅读。

Demo
<template>
    <h1>{{helloText}}</h1>
</template>
<script>
     export default{
        props:['msg'],
        data(){
            return {
                count:0, //逻辑1的数据
                name:'HelloWorld' //逻辑2的数据
            }
        },
        methods:{
            onAdd(){  //逻辑1的方法
                this.count++;
            },
            getCount(){ //逻辑2的方法
                this.count=Math.floor(Math.random()*100);
            }
        },
        computed:{
            helloText(){  //逻辑2的计算属性
               return this.msg+' '+this.name;
            }
        },
        watch:{     
            count(){  //逻辑1的watch
                console.log('count 变了');
            }
        },
        mounted(){
            this.getCount() //逻辑1的初始化操作
        }
     }
</script>
<style scoped>
  a{
    color:#42b983
  }
</style>
Vue中的函数式编程(Composition API)
介绍

Vue3采用函数式编程(Composition API)格式,该格式打破了this的限制,能够更好的复用代码,真正实现了功能的高内聚低耦合,并且更利于代码的可维护性和扩展性。

Demo
<template>
    <h1>{{helloText}}</h1>
    <button @click="count++">count is:{{count }}</button>
</template>
<script>
  import {ref,watch,computed,onMounted}from 'vue'
  export default{
    props:['msg'],
    setup(props){
        let count=ref(0);
     
        const getCount=()=>count.value=Math.floor(Math.random()*100)
        watch(count,(val,oldVal)=>{
            console.log(`count从${oldVal}变成了${val}`)
        })
        onMounted(getCount);
        let name=ref('HelloWorld');
        let helloText=computed(()=>props.msg+' '+name.value);
        return {
            count,
            name,
            helloText
        }
    }
  }
</script>
<style scoped>
a{
    color: #42b983;
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值