Global API 改为应用程序实例调用
vue2
中有很多全局api可以改变vue的行为,比如Vue.component等,这导致一些问题:
- vue2没有app概念,new Vue()得到的根实例被作为app,这样的话所有创建的根实例是共享相同的全局配置,这在测试时会污染其他测试用例,导致测试变得困难
- 全局配置也导致没有办法在单页面创建不同全局配置的多个app实例
vue3
中使用createApp
返回 app实例,由它暴露一系列全局api
import {createApp} from 'vue'
const app = createApp({}).component('comp', {render: () => h('div', 'comp component')}).mount('#app')
具体api变化:
2.x Global API | 3.x Instance API |
---|---|
Vue.config | app.config |
Vue.config.productionTip | 已移除 |
Vue.config.ignoredElements | app.config.isCustomElement |
Vue.component | app.component |
Vue.directive | app.directive |
Vue.mixin | app.mixin |
Vue.use | app.use |
Vue.filter | 已移除 |
Global and internal API 重构为可做摇树优化
摇树优化即
tree-shaking
,是一种在打包时去除没用到的代码的优化手段
vue2
存在的问题:
不少global-api
是作为静态函数直接挂在构造函数上,例如Vue.nextTick()
,如果我们从未在代码中使用它们,就会形成所谓的dead code
,这类global-api
造成的dead code
无法使用webpack
的tree-shaking
去除掉。
import Vue from 'vue';
Vue.nextTick(() => {
// something DOM-related
})
vue3
中做了相应的变化,将这些方法抽取为独立的函数,这样打包工具的摇树优化可以将这些dead code
去除掉
import {nextTick} from 'vue';
nextTick(() => {
// something DOM-related
})
受影响的api包括:
Vue.nextTick
Vue.observable (replaced by Vue。reactive)
Vue.version
Vue.compile (only in full builds)
Vue.set(only in compat builds)
Vue.delete (only in compat builds)
vue3
将很多内置特性重构为 对tree-shaking优化,这样可以使代码更小巧,如果没有使用这些特性,还不会增加网络负担,从而实现性能提升