Global data with VueJs 2

Im relatively new with VueJS, and I don't know how to make some data available around the world. I would like to save data, such as API endpoints, user data, and some other data that is retrieved from the API somewhere where each component can go to that data.
I know that I can just save this with only vanilla Javascript, but I suppose there is a way to do this with VueJS. I can use the event bus system to receive data, but I do not know how I can implement this system for my needs.

I would appreciate if anyone can help me with this.

+6
source share
2 answers

Make global data object

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

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

new Vue({
    data:{
        shared
    }
})

If you do not, you can access it inside your Vues or components, if you imported it or they are defined on the same page.

It's really that simple. You can share it as a property if you need to, or access it worldwide.

When you first start, there is no real need to complicate . Vuex is often recommended, but also often overwhelms small projects. If later you find that you need it, it is not so difficult to add it. This is also valid for state management, and it looks like you really want to access some global data.

, .

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

Vue, , . .

+16

environment.js .

var urls = {};
urls.getStudent = "api/getStudent/{id}";
etc...

environment.js , VueJS, . , .

0

Source: https://habr.com/ru/post/1016282/


All Articles