CompositionAPI
一、CompositionAPI
不同于reactivity api,composition api提供的函数很多是与组件深度绑定的,不能脱离组件而存在。
1、setup
// component
export default {
setup(props, context){
// 该函数在组件属性被赋值后立即执行,早于所有生命周期钩子函数
// props 是一个对象,包含了所有的组件属性值
// context 是一个对象,提供了组件所需的上下文信息
}
}
context对象的成员:
成员 | 类型 | 说明 |
---|---|---|
attrs | 对象 | 同vue2 的this.$attrs |
slots | 对象 | 同vue2 的this.$slots |
emit | 方法 | 同vue2 的this.$emit |
2、生命周期函数
vue2 option api | vue3 option api | vue 3 composition api |
---|---|---|
beforeCreate | beforeCreate | 不再需要,代码可直接置于setup中 |
created | created | 不再需要,代码可直接置于setup中 |
beforeMount | beforeMount | onBeforeMount |
mounted | mounted | onMounted |
beforeUpdate | beforeUpdate | onBeforeUpdate |
updated | updated | onUpdated |
beforeDestroy | 改 beforeUnmount | onBeforeUnmount |
destroyed | 改unmounted | onUnmounted |
errorCaptured | errorCaptured | onErrorCaptured |
- | 新renderTracked | onRenderTracked |
- | 新renderTriggered | onRenderTriggered |
新增钩子函数说明:
钩子函数 | 参数 | 执行时机 |
---|---|---|
renderTracked | DebuggerEvent | 渲染vdom收集到的每一次依赖时 |
renderTriggered | DebuggerEvent | 某个依赖变化导致组件重新渲染时 |
DebuggerEvent:
- target: 跟踪或触发渲染的对象
- key: 跟踪或触发渲染的属性
- type: 跟踪或触发渲染的方式
1.renderTracked
新建一个新的vue3项目,在helloworld组建中输出参数
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
count: 0
}
},
renderTracked(e) {
console.log(e);
},
renderTriggered(e) {
console.log(e);
},
}
2.renderTriggered
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
count: 0
}
},
renderTracked(e) {
console.log(e);
},
renderTriggered(e) {
console.log('renderTriggered',e);
},
}
由于依赖并没有任何变化所以,没有输出。
当依赖的count变化时,该函数就会触发。
3、composition api相比于option api有哪些优势
- 有了composition api,配合reactivity api,可以在组件内部进行更加细粒度的控制,使得组件中不同的功能高度聚合,提升了代码的可维护性。对于不同组件的相同功能,也能够更好的复用。
- 相比于option api,composition api中没有了指向奇怪的this,所有的api变得更加函数式,这有利于和类型推断系统比如TS深度配合。
博主开始运营自己的公众号啦,感兴趣的可以关注“飞羽逐星”微信公众号哦,拿起手机就能阅读感兴趣的博客啦!