Global data with VueJs 2

Make a global data object

const shared = {
    api: "http://localhost/myApi",
    mySharedMethod(){
        //do shared stuff
    }
}

If you need to expose it on your Vue, you can.

new Vue({
    data:{
        shared
    }
})

If you don’t, you can still access it inside your Vues or components if you’ve imported it or they are defined on the same page.

It’s really as simple as that. You can pass shared as a property if you need to, or access it globally.

When you’re just starting out there is no real need to get complicated. Vuex is often recommended, but is also often overkill for small projects. If, later, you find you need it, it’s not that hard to add it in. It’s also really for state management and it sounds like you just really want access to some global data.

If you want to get fancy, make it a plugin.

const shared = {
  message: "my global message"
}

shared.install = function(){
  Object.defineProperty(Vue.prototype, '$myGlobalStuff', {
    get () { return shared }
  })
}

Vue.use(shared);

Vue.component("my-fancy-component",{
  template: "<div>My Fancy Stuff: {{$myGlobalStuff.message}}</div>"
})

new Vue({
  el: "#app"
})

Now, every Vue you create and every component has access to it. Here is an example.

Leave a Comment

tech