前言
本文将通过实例代码的形式,深入的了解一下什么是组合式API,组合式API在Vue3中的用法、注意事项,以及组件间的传值方式等。
组合式API简介
我们知道Vue2中的数据、监听、计算属性和函数都是通过选项去设置的,也就是option API。
exprot default {
name: 'App',
computed: {},
watach: {}
}
在Vue3中将这些option制作成了一个个钩子(hook)函数,并在Vue3中新增了setup方法,setup方式是以选项的方式出现在vue对象中,但是像上面代码中的computed、watch等,变成了钩子函数的形式,通过vue结构出来,在setup中使用,这样就支持我们将某个功能模块封装成代码也就是所谓的组合式API,将这些代码快放到setup中使用,如下图:
import { watch, computed } from 'vue'
const api = () => {
const a = ''
return { a }
}
export default {
name: 'App',
setup() {
watch(() => {
// do something
}, () => {
// do something
})
const a = computed(() => {
// do something
})
return { ...api }
}
}
setup存在的意义就是让用可以使用新增的组合API,并且这些API只能在setup中使用。
setup执行的时机是props初始化之后,beforeCreate执行之前,所以,在执行setup的时候还没出初始化Vue实例,因此不能使用this对象。在Vue3中没有了beforeCreate和created两个生命周期,在setup中可以使用其他旧有的9个生命周期。可参照下图生命周期对照表:
| Vue 2.0 | Vue 3.0 |
|---|---|
| beforeCreate | setup() |
| created | setup() |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate |
| updated | onUpdated |
| beforeDestroy | onBeforeUnmount |
| destroyed | onUnmounted |
| activated | onActivated |
| deactivated | onDeactivated |
| errorCaptured | onErrorCaptured |
在template中使用setup函数
<template>
<div>{{ count }} {{ state.foo }}</div>
</template>
<script>
import { ref, reactive } from 'vue'
export default {
setup() {
const count = ref(0)
const state = reactive({ foo: 'bar' })
return { count, state, } // 暴露给模板
},
}
</script>
如上图,setup中有两个数据变量,count 和state用ref和reactive包裹,然后再setup中返回出来。在setup中返回出来的变量,将会暴露给Vue实例,从而实现在模板中使用。当然,这里也可以返回方法函数等。
至于这里的ref和reactive是Vue3中的响应式方法,我们将在下一节内容中讲解。