全局 API 变化”指什么

3 阅读1分钟

“全局 API 变化”指什么: 指 Vue2 里挂在全局 Vue 构造函数上的那些用法,在 Vue3 变成了 “应用实例(app)级别” 的用法:通过 createApp() 创建的 app 来配置,而不是直接 Vue.xxx。

最常见的变化对照

  • 创建应用
    • Vue2:new Vue({ render: h => h(App) }).$mount('#app')
    • Vue3:createApp(App).mount('#app')
  • 注册全局组件
    • Vue2:Vue.component('MyBtn', MyBtn)
    • Vue3:app.component('MyBtn', MyBtn)
  • 安装插件
    • Vue2:Vue.use(VueRouter) / Vue.use(ElementUI)
    • Vue3:app.use(router) / app.use(ElementPlus)
  • 全局混入
    • Vue2:Vue.mixin({...})
    • Vue3:app.mixin({...})
  • 全局指令
    • Vue2:Vue.directive('focus', ...)
    • Vue3:app.directive('focus', ...)
  • 全局属性(以前常见 Vue.prototype)
    • Vue2:Vue.prototype.$http = axios

    • Vue3:app.config.globalProperties.$http = axios 为什么要这么改: 因为 Vue3 支持 同一页面创建多个互不影响的应用实例,所以“全局配置”不再绑死在单个 Vue 全局对象上,而是归属于各自的 app。

Vue2 vs Vue3「全局 API 变化」

1) 创建应用 + 挂载

// Vue 2
import Vue from 'vue'
import App from './App.vue'

new Vue({
  render: (h) => h(App),
}).$mount('#app')
// Vue 3
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

2) 全局注册组件 / 指令 / mixin

// Vue 2
Vue.component('MyButton', MyButton)
Vue.directive('focus', { inserted(el) { el.focus() } })
Vue.mixin({ created() { /* ... */ } })
// Vue 3
const app = createApp(App)

app.component('MyButton', MyButton)
app.directive('focus', { mounted(el) { el.focus() } })
app.mixin({ created() { /* ... */ } })

3) 安装插件(router / pinia / element-plus)

// Vue 2 (示例:VueRouter)
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({ routes: [] })
new Vue({ router, render: (h) => h(App) }).$mount('#app')
// Vue 3
import router from './router'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'

const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(ElementPlus)
app.mount('#app')

4) 全局属性(以前的 Vue.prototype)

// Vue 2
import axios from 'axios'
Vue.prototype.$http = axios
// Vue 3
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$http = axios

image.png

详细的理解:

全局注册组件:

  • 先写一个可复用的组件(比如 BaseButton.vue、SvgIcon.vue、PageContainer.vue)
  • 在入口 main.ts(或单独的 plugins/components.ts)里统一注册:
  • 以后在任何页面/组件里都能直接用 ,不用每个文件都 import。 常见写法(Vue3):
import { createApp } from 'vue'
import App from './App.vue'
import BaseButton from './components/base/BaseButton.vue'

const app = createApp(App)
app.component('BaseButton', BaseButton)
app.mount('#app')

什么时候适合“全局注册”

  • 适合全局注册:全项目到处用、基础通用的“底座组件”
  • 例:SvgIcon、BaseTable、BaseForm、PageHeader、EmptyState
  • 不太适合全局注册:只在某个页面/模块用一次的业务组件
  • 这类建议局部引入,避免全局命名污染、也更利于按需加载和可维护性