Samuel Belo
Samuel Belo

Reputation: 5

How to access a method in a deep nested parent [Vue][Vuetify]

I have made a Vue component that has a v-data-table.

Child Component

    <template>
    <div>
        <v-data-table>
            <template v-slot:item.actions="{ item }">
                <v-tooltip bottom>
                    <template v-slot:activator="{ on, attrs }">
                        <v-icon @click="validation(item)"> mdi-check <v-icon/>
                    <span> Validar movimentação </span>
                </v-tooltip>
            </template>
        </v-data-table>
    </div>
</template>
<script>
export default {
        name: "ViewDraftTable",
        data() {
            return {
                movimentacoesSalvasHeader: [...]
            }
        },
        methods: {
            validation(item) {
                this.$parent.$parent.$parent.$parent.$parent.$parent.$parent.validateMov(item)
            },
        }
    }
</script>

And in the parent, I have the validate() method. How am I supposed to call this method, without having to navigate inside the nested $parents?

Upvotes: 0

Views: 419

Answers (2)

tony19
tony19

Reputation: 138216

One solution is to use provide/inject, where the parent provides the method, and a deep nested child could inject it where needed:

// Parent.vue
export default {
  provide() {
    return {
      validate(item) {
        /* perform validation */
      }
    }
  }
}

// ViewDraftTable.vue
export default {
  inject: {
    validate: {
      default: item => { /* perform default validation */ }
    }
  },
  methods: {
    validacao(item) {
      this.validate(item)
    }
  }
}

Upvotes: 1

tauzN
tauzN

Reputation: 6931

You should take a look at a state management library like Vuex

Or use provide/inject

Upvotes: 0

Related Questions