8
votes

In Vue, you can store commonly used variables and methods in the base Vue instance. This way other components can access this data.

new Vue({
    data: {
        name: 'John'
    }
}); 

If you are using Vuex for state management you could also store this data here as well.

const store = new Vuex.Store({
    state: {
       name: 'John'
    }
}

From my understanding, Vue mixins also offer the same functionality (allowing any component to access this commonly shared data globally).

Vue.mixin({
    data() {
        return {
            name: 'John'
        };
    }
});

My question is when should you use the base Vue instance over Vuex or a global mixin?

1
1) The data property in the root Vue instance should not be a function. 2) The mixin data will not be shared, it will be merged into a component's data each time it is created. 3) Any answer to question will be opinion-based as the question itself is too broad / subjectivePhil
Good catch. Will update it now. Thank you.MemUya
Are you saying that any of the methods I listed above can be used for the same purpose (sharing data across the application)? I was hoping maybe there is a specific scenario to use one over the other.MemUya
It entirely depends on what you're trying to build.Phil

1 Answers

7
votes

Vuex is a very sophisticated state management solution catering to Redux like Unidirectional/one-way data flow architecture. Use it when you need to share data across components in a sophisticated way where you need to also handle side-effects. You can also say that Vuex is nothing but a glorified implementation of Vue instance.

Vue instance, a.k.a., Vue component is meant to model your UI component. Yes, it can also serve as a State Manager and global Event Bus. But use it only for smaller apps and POC. Otherwise, Vuex is always the right choice.

Now talking about Mixins. It is not really a state management mechanism. It is meant to share reusable functionality across different components. Typically using mixins to only have data() is not a good design though. It must also have some methods that should act on that data. This is where mixins fit in overall Vue ecosystem.