Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is different between Vuex store and direct update data on $root?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading