如何设置全局商店对象?

问题描述:

我正在使用vueify和browserify。我在我的main.js文件中创建了一个对象如何设置全局商店对象?

var store = { 
foo: 'bar' 
}; 

var vm = new Vue({ 
el: '#app', 
data(){ 
    return { 
     foo: store 
    }; 
}, 

components: { 
    Login, 
    Registration, 
    ClassifiedList, 
    BusinessRegistration, 
    BusinessUpdate, 
    UserRegistration, 
    ClassifiedForm, 

    // ClassifiedKfzCreateForm, 
    // ClassifiedImmobilienCreateForm, 
    // ClassifiedImmobilienEditForm, 
    // ClassifiedKleinanzeigenCreateForm, 
    // ClassifiedJobsCreateForm 
} 

});

现在在我的Vue实例中,我可以使用它与foo.store.foo! 但是,当我使用组件中的商店对象时,商店对象是未定义的?

有人知道为什么吗?

+0

您可以将存储方法添加到window.store = {}'这样的窗口对象中。值得注意的是,这个生态系统更适合Vue cli这类使用webpack而不是browserify的工具 –

可能让您的商店全球可用的最佳方式是将其作为插件公开。

我写了一篇关于how to expose a Vuex store as a plugin for your app的博客文章。

一言以蔽之:

创建一个文件,该文件将在您的存储对象添加到主Vue原型。 Vue公司提供了一个install钩可以很容易地做到这一点:

storePlugin.js

import store from '.' // this is your store object 
export default { 
    store, 
    // we can add objects to the Vue prototype in the install() hook: 
    install (Vue, options) { 
    Vue.prototype.$myStore = store 
    } 
} 

然后在main.js,你告诉它使用你的插件:

import storePlugin from './storePlugin' 
Vue.use(storePlugin) 

,那么你会,例如,能够通过以下部件访问您的商店:

this.$myStore