Vue3全局API轉(zhuǎn)移的過程詳解
在 Vue2 到 Vue3 的升級過程中,除了響應(yīng)式系統(tǒng)、組件寫法等發(fā)生了變化,全局 API 的轉(zhuǎn)移也是一個非常重要的點。很多初學者在遷移代碼時會遇到報錯,就是因為 Vue3 不再像 Vue2 那樣把所有 API 掛在 Vue 構(gòu)造函數(shù)上了。
本文就來詳細講解一下 Vue 的全局 API 轉(zhuǎn)移。
一、什么是全局 API?
在 Vue2 中,我們經(jīng)常會寫:
import Vue from 'vue'
// 全局配置
Vue.config.productionTip = false
// 全局注冊組件
Vue.component('MyComponent', {...})
// 全局注冊指令
Vue.directive('focus', {...})
// 全局使用插件
Vue.use(MyPlugin)
// 創(chuàng)建實例
new Vue({
render: h => h(App),
}).$mount('#app')
可以看到,所有的 API(config、component、directive、use 等)都掛在 Vue 構(gòu)造函數(shù)上。
二、Vue3 為什么要轉(zhuǎn)移?
在 Vue3 中,框架的設(shè)計理念更加 模塊化 和 可樹搖(Tree-shaking)。
如果還把所有 API 都集中在 Vue 上,會導(dǎo)致以下問題:
- 包體積大:沒用到的 API 也會被打包。
- 類型推導(dǎo)差:不利于 TS 類型支持。
- 邏輯不清晰:應(yīng)用級別的配置與組件實例混在一起。
因此,Vue3 把全局 API 拆分成了更清晰的模塊。
三、Vue3 的全局 API 轉(zhuǎn)移
在 Vue3 中,所有的應(yīng)用級 API 都轉(zhuǎn)移到了由 createApp 創(chuàng)建的 應(yīng)用實例(app 實例) 上。
示例:
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)
// 掛載應(yīng)用
app.mount('#app')
對比 Vue2,你會發(fā)現(xiàn):
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 |
這樣設(shè)計的好處是:每個應(yīng)用實例都可以有自己獨立的配置,不會互相影響,非常適合 多應(yīng)用場景。
五、特殊說明
Vue.extend 被移除
Vue3 推薦使用 defineComponent 來定義組件。
import { defineComponent } from 'vue'
export default defineComponent({
props: { msg: String },
setup(props) {
return () => <div>{ props.msg }</div>
}
})
Vue.set 和 Vue.delete 移除
在 Vue3 的 Proxy 響應(yīng)式系統(tǒng)下,已經(jīng)不需要 set/delete 這種強制 API 了。
全局過濾器 Vue.filter 被移除
Vue3 建議用 方法 或 計算屬性 來替代。
六、總結(jié)
- Vue2:全局 API 都掛在
Vue構(gòu)造函數(shù)上。 - Vue3:全局 API 都轉(zhuǎn)移到了 應(yīng)用實例 app 上。
- 遷移規(guī)則:
Vue.xxx → app.xxx。 - 移除了一些過時 API(
Vue.extend、Vue.set、Vue.filter等)。
這就是所謂的 Vue 全局 API 轉(zhuǎn)移,如果面試官問到,可以從 原因、變化、示例、遷移方式 四個維度回答。
一句話精簡版回答(面試常用):
在 Vue2 中,全局 API 掛在 Vue 上;在 Vue3 中,這些 API 都遷移到由 createApp 創(chuàng)建的應(yīng)用實例上,比如 Vue.use → app.use,Vue.component → app.component,這樣做是為了支持多應(yīng)用和更好的 Tree-shaking。
以上就是Vue3全局API轉(zhuǎn)移的過程詳解的詳細內(nèi)容,更多關(guān)于Vue3全局API轉(zhuǎn)移的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue中style設(shè)置scoped后部分樣式不生效的解決
這篇文章主要介紹了vue中style設(shè)置scoped后部分樣式不生效的解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-09-09
vue 項目打包通過命令修改 vue-router 模式 修改 API 接口前綴
這篇文章主要介紹了vue 項目打包通過命令修改 vue-router 模式 修改 API 接口前綴的相關(guān)知識,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友參考下吧2018-06-06

