Search code examples
vue.jscomponentsvuetify.jsparent

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?


Solution

  • 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)
        }
      }
    }