Search code examples
vue.jscomponentsvuexvuejs3

Vue 3 - How to change data on one of multiple chid components?


I have a Vue 3 project where I have a parent component that loads other component that then loads another one that loads another one.

To give you an idea, I have a button component. The button is added multiple times in a set of numbers, the set goes into a card and the card goes into the main view component.

So 4 levels:

  • Parent Main view component with X cards (in this case I only have one)
  • Numbers Card component with X groups
  • Numbers Group component with X numbers
  • Number component used in Group

I have a binded var on the Number component that sets it active or not, by being true or false.

I want a way to set a function in my <script setup> tag in the parent top Main component (or one component inside of it) to turn one or multiple of the buttons components one and off (active true or false).

Does that makes sense?

I'm thinking if I need to use emit or just state data from my vuex data store. But I'm a bit confused on how to identify the specific button component (used multiple times) from the main parent 4 levels up component...

(In reality I want to add another type of button component there to activate that, toggle all other buttons on or off - But I think that if I understand how can from one function in one component I can access a variable in another set of components that will solve my issue...)

Let me know if this makes sense and if you can help me.

Feel free to point me to the Vue 3 Docs, I have been trying to find a solution but I'm not sure exactly where to look and because I'm using <script setup> new tag I think a lot of the examples there don't work for me.

Any little help is appreciated. Thanks so much!


Solution

  • Thanks @Matt. I ended up using the Vuex variable as an array.

    Then in my Button component I have this in my <script setup> for the isPicked variable, for example:

    const isPicked = computed(() => {
      return store.state.session.btnsPicked.find(
        (i) => i === props.btn
      )
    })
    
    

    So my component variable now reacts to the Vuex states values.