如何在外部JS文件中访问Vue实例内的全局对象
Vue外部JS文件访问全局对象解决方案
问题场景
项目中main.js定义的Vue实例包含全局数据:
new Vue({ data: { globals: { notifications: [], dynamicTabs: {} } }, render: h => h(App) }).$mount('#app')
Vue组件内可通过this.$root.globals访问并修改该全局数据,但外部独立JS文件无法通过this获取上下文,需要解决这一问题。
可行方案
1. 将Vue实例挂载到全局Window对象
修改main.js,把创建的Vue实例绑定到window:
window.vm = new Vue({ data: { globals: { notifications: [], dynamicTabs: {} } }, render: h => h(App) }).$mount('#app')
外部JS文件中直接通过全局变量访问:
// 外部js文件 vm.globals.notifications = [{ type: type, title: title, text: typeof text === 'string' ? '需提前处理国际化文本' : '带参数的国际化文本', autoDismiss: autoDismiss, dismissOnClick: dismissOnClick }]
注意:外部文件无Vue组件上下文,
this.$t无法直接使用,需提前处理好国际化文本,或把i18n实例也挂载到全局。
2. 导出Vue实例供外部导入
在main.js中导出创建的Vue实例:
const vm = new Vue({ data: { globals: { notifications: [], dynamicTabs: {} } }, render: h => h(App) }).$mount('#app') export default vm
外部JS文件中导入实例后操作:
// 外部js文件 import vm from './main.js' vm.globals.notifications = [{ type: type, title: title, text: '处理后的文本内容', autoDismiss: autoDismiss, dismissOnClick: dismissOnClick }]
3. 挂载到Vue原型(适合全局共享对象)
把globals直接挂载到Vue原型上,组件和外部文件均可访问:
// main.js Vue.prototype.$globals = { notifications: [], dynamicTabs: {} } new Vue({ render: h => h(App) }).$mount('#app') // 同时挂载到window供外部文件使用 window.$globals = Vue.prototype.$globals
外部JS文件直接使用:
// 外部js文件 $globals.notifications = [{ // 配置内容 }]
4. 使用Vuex管理全局状态(推荐中大型项目)
如果项目规模较大,用Vuex统一管理全局状态更规范,支持组件和外部文件统一操作:
首先创建store:
// store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { notifications: [], dynamicTabs: {} }, mutations: { UPDATE_NOTIFICATIONS(state, data) { state.notifications = data } }, actions: { updateNotifications({ commit }, data) { commit('UPDATE_NOTIFICATIONS', data) } } })
修改main.js引入store:
import store from './store' new Vue({ store, render: h => h(App) }).$mount('#app')
外部JS文件导入store执行修改:
// 外部js文件 import store from './store' store.dispatch('updateNotifications', [{ type: type, title: title, text: '处理后的文本', autoDismiss: autoDismiss, dismissOnClick: dismissOnClick }])
内容的提问来源于stack exchange,提问作者Selim
相关产品推荐
相关产品推荐

