1
votes

I want to share simple data between all components I know it can be done using Vuex or a global variable as a state, but it's overkill for my project!

Here is the code:

Vue.mixin({
    data: function () {
        return {
            base_url: 'http://test.develop/api/v1/',
            isLoading : false
        }
    }
})

base_url is constant and its working but isLoading must be reactive and it is not working, when I change it in one component and log it in another, it remains unchanged.

Now my question is what kind of data should be used in vue mixins ? Are mixins only for sharing code or data can be shared by mixins too?

1
Mixins are a bad idea; use vuex.Derek Pollard
We consider this approach as practical and a good trade-off in our project. Our state is rather simple but there would be many (many many) mutations and actions to the state. I think it might be a good idea.Matthias Simon

1 Answers

4
votes

Vuex will probably not be overkill. Vuex works great for small and large projects. Vue mixins are not meant for keeping global state. Mixins are the OOP equivalent of extends. You basically inherit everything that's on it through a merge, with the component having priority. It's just for shared behavior (methods, data, lifecycle).

Disclaimer: I can't think of this being accepted in the community, just take it as a learning exercise.

But the only way to have a 'global state' of sorts kept within a mixin, is to wrap its initialization object in a closure, and keep track of the information in a reactive object, like so:

Vue.mixin((()=>{
  let store = Vue.observable({
    isLoading: true
  })

  return {
    computed: {
      isLoading: {
        get(){
          return store.isLoading
        },
        set(val){
          store.isLoading = val
        }
      }
    },
  }
})())

Here's a fiddle: https://jsfiddle.net/cuzox/ptsh283w/

Again, I'm not endorsing this method 🙈