定义全局方法
约 424 字大约 1 分钟
2026-03-09
思考
如何在 Vue 中定义全局方法?
原型挂载
在 Vue 2 中,最经典的方式是将方法挂载到 Vue 构造函数的原型上。这样,所有组件实例都能通过 this 访问到该方法。
定义:
// main.js
Vue.prototype.$showToast = function(message) {
alert(message);
};使用:
// 任意组件内
export default {
methods: {
handleClick() {
this.$showToast('Hello'); // 直接通过 this 调用
}
}
};全局属性
在 Vue 3 中,弃用了 Vue.prototype 的方式,推荐使用 app.config.globalProperties 来定义全局属性。
定义:
// main.js
const app = createApp(App);
app.config.globalProperties.$showToast = (message) => {
alert(message);
};
app.mount('#app');使用(选项式):
// 选项式 API 组件
export default {
methods: {
handleClick() {
this.$showToast('Hello'); // 依然通过 this 调用
}
}
};使用(组合式):
在组合式 API 中,不再通过 this 来访问全局属性,而是通过 getCurrentInstance() 获取实例上下文才能使用,这非常繁琐且不推荐。
// setup 中不推荐的用法
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
proxy.$showToast('Hello');模块化封装
全局方法的概念可转变为“可复用的逻辑模块”。我们不再将方法挂载到实例上,而是通过 ES Module 导入。
插件封装
如果希望将一组全局方法、指令、组件打包分发,或者希望像 Vue 2 一样通过 app.use 安装,可以使用 插件系统。
定义插件:
// plugins/myPlugin.js
export default {
install(app, options) {
// 1. 添加全局方法
app.config.globalProperties.$showToast = (msg) => {
console.log(msg);
};
// 2. 注册全局组件
// app.component('MyButton', MyButton);
// 3. 提供全局注入 (推荐 Vue 3 方式)
app.provide('toast', { show: (msg) => console.log(msg) });
}
};安装插件:
// main.js
app.use(myPlugin);使用:
// 子组件
import { inject } from 'vue';
const toast = inject('toast');
toast.show('Hello');```