选项式API和组合式API的区别
Options API
- vue2中如何组织代码的:我们会在一个vue文件中
data,methods,computed,watch
中定义属性和方法,共同处理页面逻辑 - 优点:新手上手简单
-上图解释了Options API
的缺点,一个功能往往需要在不同的vue配置项中定义属性和方法,比较分散,项目小还好,清晰明了,但是项目大了后,一个methods
中可能包含很多个方法,往往分不清哪个方法对应着哪个功能,而且当你想要新增一个功能的时候你可能需要在 data,methods,computed,watch
中都要写一些东西,但是这个时候每个选项里面的内容很多你需要上下来回的翻滚,特别影响效率。
Composition API
- 缺点:学习成本可能会增加,以前的思维方式也要转变
- 优点:
Composition API
是根据逻辑相关性组织代码的,提高可读性和可维护性,基于函数组合的 API 更好的重用逻辑代码(在vue2 Options API
中通过Mixins
重用逻辑代码,容易发生命名冲突且关系不清)Composition API
最大的优点通俗的讲就是把跟一个功能相关的东西放在一个地方,它是目前最合理也是最容易维护的,你可以随时将功能的一部分拆分出去。你可以将每一个功能相关所有的东西比如methods
,computed
都放在如上图的function
中,这个function
可以独立的存在,可以放在一个TS文件中,也可在npm
中单独发布,最终Composition API
把他们组合起来
一、选项式写法
<template>
<h1>页面组件</h1>
<h1 v-text='num'></h1>
<button @click='add'>自增</button>
<button @click='sub'>自减</button>
</template>
<script>
import { ref } from 'vue'
export default {
props: { }, // 接收自定义属性
setup (props, context) {
console.log('----setup', props)
console.log('----setup', context)
const num = ref(1)
const add = () => {
num.value++
}
return { num, add }
},
methods: {
sub () { this.num-- }
},
mounted () {
console.log('---mounted')
}
}
</script>
二、组合式写法
<script setup>
import { ref } from 'vue'
const num = ref(1)
const add = () => {
num.value++
}
</script>
<template>
<h1>页面组件</h1>
<h1 v-text='num'></h1>
<button @click='add'>自增</button>
</template>
三、JSX 写法
为了支持 JSX语法,需要先安装 【@vitejs/plugin-vue-jsx】 插件,并在vite.config.js中进行配置,参考文档:点这里!
import { defineComponent, ref, computed, watch } from 'vue'
export default defineComponent((props) => {
const num = ref(1)
const add = () => {
num.value++
}
// 监听器
watch(num, ()=>{
console.log('---num changed', num.value)
})
// 计算属性
const total = computed(()=>(num.value*1000))
return () => (
<div>
<h1>页面组件</h1>
<h1>{ num.value }</h1>
<h1>{ total.value }</h1>
<button onClick={add}>自增</button>
</div>
)
})
Vue3编写组件的语法范式非常多,也很自由。从最新发展看,官方更推荐使用 <script setup>语法糖的写法。