Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use the base Vue instance, Vuex or mixin?

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?

like image 629
MemUya Avatar asked Jan 07 '19 04:01

MemUya


People also ask

What is the benefit of using mixins in Vuejs?

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component's own options.

Is Vuex necessary in vue3?

Let's take a look at why Vuex is is still necessary, even in Vue 3. First, Vuex offers advanced debugging capabilities that Vue 3 features does not. This is a huge bonus for developers, since no one wants to spend all that time debugging! Secondly, Vuex has plugins that extend its capabilities.

What is the difference between Vue and Vuex?

Vue is a progressive Javascript framework and Vuex is the state management tool. We can use redux or flux inside Vue, But Vuex is native to the Vue.


1 Answers

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.

like image 161
Harshal Patil Avatar answered Sep 27 '22 20:09

Harshal Patil