I want to update the data to root instance from nested components. I know that use $emit
can update the data to parent component. But it's no efficiency if the component inside many layers from root.
I took a look on Vuex
and it seems solve this situation nicely. But I wonder why don't just set this.$root.value = newValue
like the following:
// Root
new Vue({
data: {
value: ''
}
})
// Nested Child
<template>
<input type="text" @input="onInput" />
</template>
<script>
export default {
methods: {
onInput: function(event){
this.$root.value = event.target.value;
},
}
}
</script>
I want to know that what's different between the two. Thanks.
CodePudding user response:
I think you absolutely can rely on root state itself, but state management libraries helps to organize your code so many ways.
Due to using a single state tree, all states of your app are contained inside one big object.
As your app grows bigger and bigger this state tree gets really hard to handle.
For example, if you have one source of truth shared across multiple component like this:
var sourceOfTruth = {}
var vmA = new Vue({
data: sourceOfTruth
})
var vmB = new Vue({
data: sourceOfTruth
})
Works perfectly, but both components can mutate this state, so good luck debugging what and where went wrong if the state gets dirty somewhere. Any piece of data could be changed by any part of our app at any time, without leaving a trace.
This alone is a good reason to use a state management library, but vuex gives other useful tools too.
Just to mention a few: Vuex allows you to divide the store into modules. Each module can contain its own state, mutations, actions, getters, and even nested modules. If you want your modules to be more self-contained or reusable, you can mark it with namespaces as well.
I hope I could clarify a bit for you. State management rocks!
For details look at the docs:
https://v2.vuejs.org/v2/guide/state-management.html
https://vuex.vuejs.org/guide/modules.html
CodePudding user response:
VueX (or Pinia a lightweight alternative) act as powerful state management storage, not only allowing you to access the data from anywhere in your application (like a database) but also tieing additional logic to process or chain other actions to the data you're updating.
You can also organise your VueX store into multiple files to keep your codebase organised and ready to scale, meaning anyone jumping on to the project knows where to find globally accessible data.
Hope that helps inform your decision.