2016-06-08 97 views
3

我正在使用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的工具 –

回答

4

可能讓您的商店全球可用的最佳方式是將其作爲插件公開。

我寫了一篇關於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