vue 公共的方法实现
在 Vue 中实现公共方法的几种方式
使用 Mixin Mixin 是一种分发 Vue 组件中可复用功能的灵活方式。可以定义一个包含公共方法的 Mixin,然后在多个组件中混入。
// 定义公共方法 Mixin
const commonMethodsMixin = {
methods: {
formatDate(date) {
// 日期格式化逻辑
},
showToast(message) {
// 显示提示信息
}
}
}
// 在组件中使用
export default {
mixins: [commonMethodsMixin],
// 组件其他选项
}
使用插件 对于需要在全局使用的公共方法,可以开发 Vue 插件。

// 定义插件
const CommonMethodsPlugin = {
install(Vue) {
Vue.prototype.$common = {
formatCurrency(value) {
// 货币格式化
},
deepClone(obj) {
// 深拷贝
}
}
}
}
// 在 main.js 中使用
Vue.use(CommonMethodsPlugin)
// 在任何组件中调用
this.$common.deepClone(someObject)
使用工具模块 创建独立的工具模块,按需导入使用。
// utils/common.js
export function debounce(fn, delay) {
// 防抖函数实现
}
export function throttle(fn, interval) {
// 节流函数实现
}
// 在组件中使用
import { debounce } from '@/utils/common'
export default {
methods: {
handleInput: debounce(function() {
// 处理输入
}, 300)
}
}
使用 Provide/Inject 对于需要跨多级组件共享的方法,可以使用 provide/inject。

// 祖先组件
export default {
provide() {
return {
commonMethods: {
formatTime: this.formatTime
}
}
},
methods: {
formatTime(timestamp) {
// 时间格式化
}
}
}
// 后代组件
export default {
inject: ['commonMethods'],
created() {
this.commonMethods.formatTime(Date.now())
}
}
使用 Vuex 如果方法需要管理状态或涉及多个组件交互,可以使用 Vuex。
// store/modules/common.js
export default {
actions: {
showLoading({ commit }) {
commit('SET_LOADING', true)
},
hideLoading({ commit }) {
commit('SET_LOADING', false)
}
}
}
// 在组件中使用
this.$store.dispatch('common/showLoading')
选择哪种方式取决于具体需求:
- 组件间复用:Mixin 或工具模块
- 全局使用:插件或 Vuex
- 跨层级组件:provide/inject
- 涉及状态管理:Vuex






