ps:感谢评论区小伙伴提出的疑问:如果你的项目是在vue2.x的基础上,再安装Composition API 来开发的,那么, setup 函数,会在 beforeCreate 之后created 之前执行!如果你是直接通过vue add vue-next安装最新的 vue3.0.x beta,那么setup会在beforeCreate和created之前执行!
新钩子
除了2.x生命周期等效项之外,Composition API还提供了以下debug hooks:
onRenderTracked
onRenderTriggered
两个钩子都收到DebuggerEvent类似于onTrack和onTrigger观察者的选项:
export default {
onRenderTriggered(e) {
debugger
// inspect which dependency is causing the component to re-render
}
}依赖注入
provide和inject启用类似于2.x provide/inject选项的依赖项注入。两者都只能在setup()当前活动实例期间调用。
import { provide, inject } from '@vue/composition-api'const ThemeSymbol = Symbol()
const Ancestor = {
setup() {
provide(ThemeSymbol, 'dark')
}
}
const Descendent = {
setup() {
const theme = inject(ThemeSymbol, 'light' /* optional default value */)
return {
theme
}
}
}
inject接受可选的默认值作为第二个参数。如果未提供默认值,并且在Provide上下文中找不到该属性,则inject返回undefined。
注入响应式数据
为了保持提供的值和注入的值之间的响应式,可以使用ref
// 在父组建中
const themeRef = ref('dark')
provide(ThemeSymbol, themeRef)// 组件中
const theme = inject(ThemeSymbol, ref('light'))
watchEffect(() => {
console.log(`theme set to: ${theme.value}`)
})
因为setup函数接收2个形参,第一个是initProps,即父组建传送过来的值!,第二个形参是一个上下文对象
setupContext,这个对象的主要属性有 :
attrs: Object // 等同 vue 2.x中的 this.$attrs
emit: ƒ () // 等同 this.$emit()
isServer: false // 是否是服务端渲染
listeners: Object // 等同 vue2.x中的this.$listeners
parent: VueComponent // 等同 vue2.x中的this.$parent
refs: Object // 等同 vue2.x中的this.$refs
root: Vue // 这个root是我们在main.js中,使用newVue()的时候,返回的全局唯一的实例对象,注意别和单文件组建中的this混淆了
slots: {} // 等同 vue2.x中的this.$slots
ssrContext:{} // 服务端渲染相关⚠️注意:在 setup() 函数中无法访问到 this的,不管这个this指的是全局的的vue对象(即:在main.js 中使用new生成的那个全局的vue实例对象),还是指单文件组建的对象。










