vue实现单例
Vue 实现单例模式的方法
在 Vue 中实现单例模式通常用于确保某个对象或组件在整个应用中只存在一个实例。以下是几种常见的实现方式:
使用 Vue 插件
通过 Vue 插件机制注册全局服务,确保单例。

// singleton.js
const SingletonPlugin = {
install(Vue) {
const instance = new Vue({
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
}
})
Vue.prototype.$singleton = instance
}
}
// main.js
import Vue from 'vue'
import SingletonPlugin from './singleton'
Vue.use(SingletonPlugin)
// 使用
this.$singleton.increment()
使用 ES6 模块
利用 ES6 模块的单例特性实现。

// singleton.js
let instance = null
export default class Singleton {
constructor() {
if (!instance) {
instance = this
this.count = 0
}
return instance
}
increment() {
this.count++
}
}
// 使用
import Singleton from './singleton'
const singleton = new Singleton()
singleton.increment()
使用 Vuex
通过 Vuex 的状态管理实现单例效果。
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
// 使用
this.$store.commit('increment')
使用 provide/inject
在 Vue 3 中可以通过 provide/inject 实现单例。
// main.js
import { createApp } from 'vue'
const app = createApp({})
app.provide('singleton', {
count: 0,
increment() {
this.count++
}
})
// 使用
import { inject } from 'vue'
const singleton = inject('singleton')
singleton.increment()
注意事项
- 单例模式可能导致全局状态难以追踪,需谨慎使用
- 在 SSR 场景下,单例可能导致内存泄漏
- 优先考虑 Vuex 或 Pinia 等状态管理方案替代全局单例






