How to update component's data property from another component in vuejs?

Viewed 1265

I have two components A & B, both are not child or parent of each other. A has data as

export default {
    data() {
        return { 
           info1: 'info1'
        }
    }
}

Now I want to update this info1 proppoerty from component B. Is it possible?

2 Answers

You can use $root and $refs for this, attach ref to both components, like:

<component-a ref="compa"></component-a>
<component-b ref="compb"></component-b>

Now here is the important part, you need to follow the exact path to each component.Example you want to access component A in B, use

this.$root.$children[0].$refs.compa.info1

or it would be

this.$root.$children[0].$children[0].$refs.compa.info1

or

this.$root.$children[0].$children[1].$refs.compa.info1

According to your app and components relation to each other. In this way you can access and update the info1 from component A.This is one way to achieve it.

Yes it's possible in more than one way. I would suggest using Vuex for this, as it makes things easier down the road when multiple components need to grab/update values.

Vuex is a library for state management and are thus build for what you are trying to achieve. It also makes it a lot easier to inspect values during development.

Related