我正在使用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一起使用! 但是当我在组件中使用store对象时,store对象是未定义的?
有人知道为什么吗?
答案 0 :(得分:9)
使您的商店全球可用的最佳方式可能是将其作为插件公开。
我写了一篇关于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