vue实现全局共享
全局状态管理方案
在Vue中实现全局共享状态,通常指多个组件间共享数据或方法。以下是几种常见方案:
Vuex状态管理库
Vuex是Vue官方推荐的状态管理库,适合中大型应用:
安装Vuex:
npm install vuex --save
创建store实例:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
doubleCount: state => state.count * 2
}
})
export default store
在组件中使用:
// 获取state
this.$store.state.count
// 触发mutation
this.$store.commit('increment')
// 触发action
this.$store.dispatch('incrementAsync')
// 使用getter
this.$store.getters.doubleCount
使用provide/inject
适合小型应用或组件库开发,实现跨层级组件通信:
父组件提供数据:
export default {
provide() {
return {
sharedData: this.sharedState
}
},
data() {
return {
sharedState: {
message: '全局数据'
}
}
}
}
子组件注入数据:
export default {
inject: ['sharedData'],
created() {
console.log(this.sharedData.message)
}
}
全局事件总线
创建事件中心实现组件间通信:
创建事件总线:

// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
发送事件:
import { EventBus } from './eventBus.js'
EventBus.$emit('event-name', payload)
接收事件:
import { EventBus } from './eventBus.js'
EventBus.$on('event-name', payload => {
// 处理事件
})
使用Vue.observable
Vue 2.6+引入的响应式API,适合简单状态管理:
创建响应式对象:
// store.js
import Vue from 'vue'
export const state = Vue.observable({
count: 0
})
export const mutations = {
setCount(count) {
state.count = count
}
}
组件中使用:

import { state, mutations } from './store'
export default {
computed: {
count() {
return state.count
}
},
methods: {
setCount(count) {
mutations.setCount(count)
}
}
}
Pinia状态管理库
Vue3推荐的状态管理方案,比Vuex更简洁:
安装Pinia:
npm install pinia
创建store:
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
在组件中使用:
import { useCounterStore } from '@/stores/counter'
export default {
setup() {
const counter = useCounterStore()
return {
counter
}
}
}
全局混入(mixin)
共享组件选项,谨慎使用:
定义全局mixin:
Vue.mixin({
data() {
return {
globalData: '共享数据'
}
},
methods: {
globalMethod() {
console.log('全局方法')
}
}
})
选择建议
- 小型应用:使用provide/inject或Vue.observable
- 中型应用:Vuex或Pinia
- 组件库开发:优先考虑provide/inject
- 需要事件通信:使用事件总线
- Vue3项目:推荐使用Pinia
每种方案都有适用场景,需根据项目规模和复杂度选择最合适的方式。






