Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a global store Object?

I am working with vueify and browserify. I have made an object in my main.js file

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
}

});

Now in my Vue Instance I can use it with foo.store.foo ! But when I am use the store object in an component, the store object is undefined?

Does anybody know why?

like image 779
Wolfgang Müller Avatar asked Jan 27 '26 07:01

Wolfgang Müller


1 Answers

Probably the best way to make your store globally available would be to expose it as a plugin.

I wrote a blog post about how to expose a Vuex store as a plugin for your app.

In a nutshell:

Create a file which will add your store object to the main Vue prototype. Vue provides an install hook to make it easy to do this:

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
  }
}

And then in main.js, you tell it to use your plugin:

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

You would then, for example, be able to access your store from a component via:

this.$myStore
like image 154
toast38coza Avatar answered Jan 28 '26 21:01

toast38coza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!