Nuxt / Vue:组件调用页面中的方法

Nuxt / Vue : Component call a Method in a page

我的问题是:

我的页面listing.vue列出所有产品。 这些产品在组件中,Product.vue

在此组件中,有一个按钮可将此产品添加到选择中,显示在 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>

问题是nuxt渲染错误:

the addToSelection method is unknown.

您应该从 children 发射到 parent

Product.vue

<button @click="emitProductToParent(product.id)">

...
methods: {
  emitProductToParent(id) {
    this.$emit('input', id)
  }
}

Listing.vue

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

您不能使用不在您的事件侦听器所在的组件中的方法。即使可以,这也不是办法。使用:

  • 道​​具传递给 children
  • 发射以传递最多 parents

如官方文档中所述:https://vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events