Vue3 全局 API 变更
全局API和配置
- 从技术上讲,
Vue 2
没有“app”的概念,我们定义的应用只是通过new Vue()
创建的根 Vue 实例。从同一个Vue
构造函数创建的每个根实例共享相同的全局配置 - 大致意思就是 如果创建了多个
Vue
根实例,他们也会共享Vue.use()
Vue.minx()
等一些全局配置,不利于 Vue 项目的测试等一些操作
- 从技术上讲,
createApp
- 调用 createApp 返回一个应用实例
import { createApp } from 'vue'
const app = createApp({})
v2 => v3
2.x 全局 API 3.x 实例 API (app) 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.prototype app.config.globalProperties - 所有其他不全局改变行为的全局 API 现在被命名为 exports,文档见全局 API Treeshaking。
插件使用
import { VueRouter } from 'vue-router'
import { createApp } from 'vue'
const app = createApp({});
app.use(VueRouter);
挂载 App 实例
import { VueRouter } from 'vue-router'
import { createApp } from 'vue'
import App from './App'
const app = createApp(App);
app.component('button-counter', {
data: () => ({
count: 0
}),
template: '<button @click="count++">Clicked {{ count }} times.</button>'
})
app.directive('focus', {
mounted: el => el.focus()
})
app.use(VueRouter);
app.mount('#app');
Provide / Inject
- 可被应用内任意组件注入的依赖项
- app.provide(‘tips’,‘成功’) ,任意组件可通过 inject(‘tips’) 接收参数
在应用之间共享配置
- 在应用之间共享配置 (如组件或指令) 的一种方法是创建工厂函数
import { createApp } from 'vue'
import Foo from './Foo.vue'
import Bar from './Bar.vue'
const createMyApp = options => {
const app = createApp(options)
app.directive('focus', /* ... */)
return app
}
createMyApp(Foo).mount('#foo')
createMyApp(Bar).mount('#bar')
全局 API Treeshaking
- 使用的时候需要单独引入
- import { nextTick } from ‘vue’
- …
- wepack打包将 Vue 从最终的打包产物中排除
- 具体使用方法 Vue 配置使用 externals 使用cdn减小打包体积 (前端优化)
// webpack.config.js
module.exports = {
/*...*/
externals: {
vue: 'Vue'
}
}