问题
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:
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.
来源:https://stackoverflow.com/questions/54068494/when-to-use-the-base-vue-instance-vuex-or-mixin