Vue3进阶主题Composition API使用详解
Composition API 是 Vue3 中引入的一种新的 API 风格,旨在提高代码的可读性、可维护性和可重用性。Composition API 不同于 Vue2 中的 Options API,它采用了一种基于函数的编程方式,将组件内的逻辑分解成更小的可组合函数单元,以实现更加灵活和高效的代码组织方式。
为什么Vue3推荐使用Composition API
Vue3 推荐使用 Composition API 的主要原因是为了更好地组织和重用组件逻辑。
在 Vue2 中,我们通常使用 Options API,其中我们通过定义不同的选项(如 data、methods、computed 等)来定义组件的行为。这种方式存在一些缺点,例如:
大型组件变得难以维护,因为相关代码被分散在不同的选项中。
大型组件可能会有重复的逻辑,因为代码难以重用。
跟踪哪些数据属性被修改以及在何时修改它们可能变得困难。
我们下面举个简单例子, 以下代码定义了一个用于获取数据的逻辑:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { reactive, onMounted } from
'vue'
import axios from
'axios'
export
function
useData(url) {
const data = reactive({
loading:
false
,
error:
null
,
items: []
})
const fetchData = async () => {
data.loading =
true
try
{
const response = await axios.get(url)
data.items = response.data
}
catch
(error) {
data.error = error.message
}
data.loading =
false
}
onMounted(() => {
fetchData()
})
return
{
data,
fetchData
}
}
可以看到,该逻辑包括了获取数据的方法和处理加载状态、错误信息等的逻辑。我们可以在多个组件中使用该逻辑,避免了重复的代码。
例如,在一个组件中使用该逻辑:
1
2
3
4
5
6
7
8
9
import { useData } from
'./useData'
export
default
{
setup() {
const { data } = useData(
'https://api.example.com/data'
)
return
{
data
}
}
}
当然, Vue2通过mixin
也能实现上面的功能, 但可读性和可维护性不如Composition API:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const dataMixin = {
data() {
return
{
loading:
false
,
error:
null
,
items: []
}
},
methods: {
fetchData() {
this
.loading =
true
axios.get(
this
.url)
.then(response => {
this
.items = response.data
})
.
catch
(error => {
this
.error = error.message
})
.finally(() => {
this
.loading =
false
})
}
},
mounted() {
this
.fetchData()
}
}
然后在组件中使用:
1
2
3
4
5
6
7
8
export
default
{
mixins: [dataMixin],
data() {
return
{
url:
'https://api.example.com/data'
}
}
}
可以看到,使用mixin
可以将公共的逻辑混入到组件中,但是混入存在一些问题,例如命名冲突、生命周期钩子的调用顺序等问题。