代码逻辑
在代码逻辑方面,options api同一个功能的代码会被拆散到不同配置项中:data、methods、computed、watch、生命周期中。而composition api更接近于原生js,实现代码逻辑聚合。
复用
再代码复用方面,vue2主要使用mixin,但mixin存在一些问题:
- 变量冲突;
mixinA.methods.getList
mixinB.methods.getList
后者会进行覆盖。
- 全量混入;
- 来源不清晰。
无法看出
来源哪个组件this.getList()
使用composition api后,可以将相关的逻辑抽取成独立的函数(Composable组合式函数),在不同组件中直接引入,这种ESM静态导入的方式也更有利于Tree Shaking。
代码压缩
vue组件由template和script组成。
在options api中:
- template会被编译为渲染函数
- script最终会导出一个组件实例对象 例如:
function render(_ctx) {
return _createElementVNode("div", null, toDisplayString(_ctx.userInfo))
}
_ctx就是组件渲染上下文,是一个js对象,因此“userInfo”不能被压缩为“a”。
在composition api中:
也会编译为一个render渲染函数,但是,setup 中的变量会成为 render 的闭包变量,如下:
function render() {
setup(__props) {
const userInfo = ref("Gemini")
return (_ctx, _cache) => {
return(openBlock(),createElementBlock("div",null,toDisplayString(userInfo.value),1))
}
}
}
创建应用
vue2使用new Vue()的方式创建应用,存在一些问题:
- 使用实例化的方式,会使得应用能获取到Vue对象的所有属性和方法,不管有没有用到。
- 全局挂载的指令、插件等,对所有应用都生效,无法区分。
vue3使用const app = createApp()的方式创建应用,使得所需的属性函数进行按需导入,不必全部继承;挂载指令插件是单独对某一应用进行挂载。