目录
[一、什么是全局 API?](#一、什么是全局 API?)
[二、Vue3 为什么要转移?](#二、Vue3 为什么要转移?)
[三、Vue3 的全局 API 转移](#三、Vue3 的全局 API 转移)
[四、常见 API 的迁移对照表](#四、常见 API 的迁移对照表)
在 Vue2 到 Vue3 的升级过程中,除了响应式系统、组件写法等发生了变化,全局 API 的转移也是一个非常重要的点。很多初学者在迁移代码时会遇到报错,就是因为 Vue3 不再像 Vue2 那样把所有 API 挂在 Vue 构造函数上了。
本文就来详细讲解一下 Vue 的全局 API 转移。
一、什么是全局 API?
在 Vue2 中,我们经常会写:
javascript
import Vue from 'vue'
// 全局配置
Vue.config.productionTip = false
// 全局注册组件
Vue.component('MyComponent', {...})
// 全局注册指令
Vue.directive('focus', {...})
// 全局使用插件
Vue.use(MyPlugin)
// 创建实例
new Vue({
render: h => h(App),
}).$mount('#app')
可以看到,所有的 API(config
、component
、directive
、use
等)都挂在 Vue
构造函数上。
二、Vue3 为什么要转移?
在 Vue3 中,框架的设计理念更加 模块化 和 可树摇(Tree-shaking) 。
如果还把所有 API 都集中在 Vue
上,会导致以下问题:
-
包体积大:没用到的 API 也会被打包。
-
类型推导差:不利于 TS 类型支持。
-
逻辑不清晰:应用级别的配置与组件实例混在一起。
因此,Vue3 把全局 API 拆分成了更清晰的模块。
三、Vue3 的全局 API 转移
在 Vue3 中,所有的应用级 API 都转移到了由 createApp
创建的 应用实例(app 实例) 上。
示例:
javascript
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 全局配置
app.config.globalProperties.$http = () => {}
// 全局注册组件
app.component('MyComponent', {...})
// 全局注册指令
app.directive('focus', {...})
// 全局使用插件
app.use(MyPlugin)
// 挂载应用
app.mount('#app')
对比 Vue2,你会发现:
Vue.xxx
变成了 app.xxx
。
四、常见 API 的迁移对照表
Vue2 写法 | Vue3 写法 |
---|---|
Vue.config |
app.config |
Vue.component |
app.component |
Vue.directive |
app.directive |
Vue.mixin |
app.mixin |
Vue.use |
app.use |
Vue.prototype |
app.config.globalProperties |
这样设计的好处是:每个应用实例都可以有自己独立的配置,不会互相影响,非常适合 多应用场景。
五、特殊说明
-
Vue.extend
被移除Vue3 推荐使用
defineComponent
来定义组件。javascriptimport { defineComponent } from 'vue' export default defineComponent({ props: { msg: String }, setup(props) { return () => <div>{ props.msg }</div> } })
-
Vue.set
和Vue.delete
移除在 Vue3 的 Proxy 响应式系统下,已经不需要
set/delete
这种强制 API 了。 -
全局过滤器
Vue.filter
被移除Vue3 建议用 方法 或 计算属性 来替代。
六、总结
-
Vue2:全局 API 都挂在
Vue
构造函数上。 -
Vue3:全局 API 都转移到了 应用实例 app 上。
-
迁移规则:
Vue.xxx → app.xxx
。 -
移除了一些过时 API(
Vue.extend
、Vue.set
、Vue.filter
等)。
这就是所谓的 Vue 全局 API 转移 ,如果面试官问到,可以从 原因、变化、示例、迁移方式 四个维度回答。
一句话精简版回答(面试常用):
在 Vue2 中,全局 API 挂在 Vue 上;在 Vue3 中,这些 API 都迁移到由 createApp
创建的应用实例上,比如 Vue.use
→ app.use
,Vue.component
→ app.component
,这样做是为了支持多应用和更好的 Tree-shaking。