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>