← 返回完整题库
vue.js困难

怎么在 Vue 中定义全局方法?

参考答案

分场景

| 目的 | 做法 |
|---|---|
| 模板里能用的全局方法 | app.config.globalProperties.$fmt = fmt,模板 {{ $fmt(x) }} |
| 任何地方 import 的工具 | 独立模块 utils/fmt.js 导出(最推荐:可 tree-shake、可测、无污染) |
| 组合式函数 | useXxx()(useRequest、usePermission),按需引入 |
| 全局组件 | app.component('MyBtn', MyBtn) |
| 全局指令 | app.directive('focus', {...}) |
| 依赖注入(推荐) | app.provide('$http', http) + inject('$http') |
| 全局 mixin(不推荐) | app.mixin({ methods: { $a(){} } }),影响所有组件、来源不明 |
| Vue 2 | Vue.prototype.$xxx = xxx |

const app = createApp(App)
app.config.globalProperties.$formatDate = formatDate
app.provide('$http', httpClient)
app.mount('#app')

// 组件内
const http = inject('$http')

注意

  1. globalProperties 不是响应式的,只放方法/常量,别挂可变状态(多 app 实例会冲突);
  2. TS 要补类型:
declare module 'vue' {
  interface ComponentCustomProperties { $formatDate: (d: Date) => string }
}
export {}
  1. **不推荐用 getCurrentInstance().proxy** 做生产逻辑,官方建议显式 inject/import(利于 SSR 与单测);
  2. 别 this.$xxx 满天飞,全局挂载只保留真正全局高频的(i18n、权限判断)。

本题来自 计算机知识面试题库,共 921 道题。