In Vue, you can store monly used variables and methods in the base Vue instance. This way other ponents 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 ponent to access this monly 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?
In Vue, you can store monly used variables and methods in the base Vue instance. This way other ponents 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 ponent to access this monly 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?
Share Improve this question edited Jan 7, 2019 at 4:38 MemUya asked Jan 7, 2019 at 4:17 MemUyaMemUya 3474 silver badges13 bronze badges 4-
1) The
data
property in the rootVue
instance should not be a function. 2) The mixin data will not be shared, it will be merged into a ponent's data each time it is created. 3) Any answer to question will be opinion-based as the question itself is too broad / subjective – Phil Commented Jan 7, 2019 at 4:36 - Good catch. Will update it now. Thank you. – MemUya Commented Jan 7, 2019 at 4:38
- 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 Commented Jan 7, 2019 at 4:40
- It entirely depends on what you're trying to build. – Phil Commented Jan 7, 2019 at 4:41
1 Answer
Reset to default 7Vuex
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 ponents 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 ponent is meant to model your UI ponent. 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 ponents. 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.