网络工程师自学网站,怎样在百度上做网站,科技感网页设计,今天的三个新闻面试题#xff1a;composition api相比于option api有哪些优势#xff1f; 不同于reactivity api#xff0c;composition api提供的函数很多是与组件深度绑定的#xff0c;不能脱离组件而存在。
1. setup
// component
export default {setup(props, context){// 该函数在… 面试题composition api相比于option api有哪些优势 不同于reactivity apicomposition api提供的函数很多是与组件深度绑定的不能脱离组件而存在。
1. setup
// component
export default {setup(props, context){// 该函数在组件属性被赋值后立即执行早于所有生命周期钩子函数// props 是一个对象包含了所有的组件属性值// context 是一个对象提供了组件所需的上下文信息}
}context对象的成员
成员类型说明attrs对象同vue2的this.$attrsslots对象同vue2的this.$slotsemit方法同vue2的this.$emit
2. 生命周期函数
vue2 option apivue3 option apivue 3 composition apibeforeCreatebeforeCreate不再需要代码可直接置于setup中createdcreated不再需要代码可直接置于setup中beforeMountbeforeMountonBeforeMountmountedmountedonMountedbeforeUpdatebeforeUpdateonBeforeUpdateupdatedupdatedonUpdatedbeforeDestroy改 beforeUnmountonBeforeUnmountdestroyed改unmountedonUnmountederrorCapturederrorCapturedonErrorCaptured-新renderTrackedonRenderTracked-新renderTriggeredonRenderTriggered
新增钩子函数说明
钩子函数参数执行时机renderTrackedDebuggerEvent渲染vdom收集到的每一次依赖时renderTriggeredDebuggerEvent某个依赖变化导致组件重新渲染时
DebuggerEvent:
target: 跟踪或触发渲染的对象key: 跟踪或触发渲染的属性type: 跟踪或触发渲染的方式
App.vue
templateimg altVue logo src./assets/logo.png /HelloWorld msgHello Vue 3.0 Vite /
/templatescript
import HelloWorld from ./components/HelloWorld.vueexport default {name: App,components: {HelloWorld}
}
/script
HelloWorld .vue
templateh1{{ msg }}/h1button clickcountcount is: {{ count }}/buttonpEditcodecomponents/HelloWorld.vue/codeto test hot module replacement./p
/templatescript
export default {name: HelloWorld,props: {msg: String,},data() {return {count: 0,};},renderTracked(e) {console.log(e); //count},renderTriggered(e) {console.log(renderTriggered, e); //msg或者count},
};
/script
3. 面试题参考答案
面试题composition api相比于option api有哪些优势 从两个方面回答 为了更好的逻辑复用和代码组织更好的类型推导 有了composition api配合reactivity api可以在组件内部进行更加细粒度的控制使得组件中不同的功能高度聚合提升了代码的可维护性。对于不同组件的相同功能也能够更好的复用。
相比于option apicomposition api中没有了指向奇怪的this所有的api变得更加函数式这有利于和类型推断系统比如TS深度配合。