【问题标题】:How to setup a global store Object?如何设置全局存储对象?
【发布时间】:2016-10-09 06:26:03
【问题描述】:

我正在使用 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 对象是未定义的?

有人知道为什么吗?

【问题讨论】:

  • 您可以将 store 方法附加到窗口对象,例如 window.store = {}。值得注意的是,生态系统更适合 Vue cli 等使用 webpack 而不是 browserify 的工具

标签: vue.js vue-component


【解决方案1】:

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

我写了一篇关于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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2014-10-27
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多