Search code examples
vue.jsmethodscomponentsnuxt.js

Nuxt / Vue : Component call a Method in a page


There is my issue:

My page listing.vue list all products. Theses products are in a Component, Product.vue.

In this component, there is a button to add this product to a selection, displaying on the listing.vue.

page/listing.vue :

<template>
  <div>
    <product v-for="...." />
     
    <section>
      <ul>
        <li>Produit 1</li>
        <li>Produit 3</li>
    </section>
  </div>
</template>

<script>
export default {
  methods: {
    addToSelection(id) {
      // Code to add Product to <ul> //
    }
  }
}
</script>

component/product.vue:

<template>
  <div>
    {{ product.title }}
    <button @click="addToSelection(product.id)">
      Add product to selection
    </button>
  </div>
</template>

<script>
export default {
  props: ['product'],
}
</script>

The problem is nuxt render an error:

the addToSelection method is unknown.


Solution

  • You should emit from your children to your parent

    Product.vue

    <button @click="emitProductToParent(product.id)">
    
    ...
    methods: {
      emitProductToParent(id) {
        this.$emit('input', id)
      }
    }
    

    Listing.vue

    <Product @input="addToSelection" v-for="...." />
    

    You cannot use a method that is not in the component your event listener is on. And even if you could, this is not the way to do. Use:

    • props to pass things down to children
    • emit to pass things up to parents

    As explained in the official documentation here: https://v2.vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events