【问题标题】:Vue, multiple instances of same component handling events in some strange wayVue,相同组件的多个实例以某种奇怪的方式处理事件
【发布时间】:2021-09-06 14:48:09
【问题描述】:

我正在尝试使用相同组件的两个实例。 我实现了两个方法,当两个实例之一发出事件时应该调用它们。 两个实例的唯一区别是instance1应该调用method1,instance2应该调用method2。

无论哪个组件发出事件,都会调用 method1。

我错过了什么吗?

这是我正在做的一个简短示例

自定义组件

<template>
....// Some code that at a certain point calls myMethod
</template>
<script>
export default {
  methods: {
    myMethod () {
      this.$emit('picture-taken')
    }
  }
}
</script>

我使用 CustomComponent 的页面

<template>
  <custom-component @picture-taken="func1" />
  <custom-component @picture-taken="func2" />
</template>

<script>
export default {
  methods: {
    func1() {
      debugger
      //It always ends up here
    },
    func2() {
      debugger
    },
  }
}
</script>

【问题讨论】:

  • 这里,您写的是“如果发生@picture-taken 事件,请致电func1func2”。由于您在两个组件上都有侦听器,因此将调用这两个方法。这完全符合预期。
  • 但是有两个独立的实例应该彼此独立地存在。如果我在第一个实例上做某事,它应该调用 func1,否则调用 func2。它总是调用第一个(不是两个)
  • 他们的数据和生命周期确实存在。但是在这里,您确实在 parent 范围内侦听了一个事件,除此之外,您确实有一个 debugger,它可能会阻塞代码,使其无法到达 func2
  • 如果有帮助,我还尝试将一个函数作为道具传递给组件,然后我调用了该函数,而不是发出事件。结果相同,只有 func1 被调用。 func2 永远不会被调用,无论是否是调试器。
  • 在 Vue 中,你不应该在 props 中传递函数。

标签: javascript vue.js events nuxt.js


【解决方案1】:

这种代码适用于您的用例。

parent page

<template>
  <div>
    <child :id="1" @picture-taken="callSpecificFunction"></child>
    <child :id="2" @picture-taken="callSpecificFunction"></child>
  </div>
</template>

<script>
export default {
  auth: false,
  methods: {
    callSpecificFunction(id) {
      console.log('id emitted', id)
      this[`function${id}`]()
    },
    function1() {
      console.log('function1 called')
    },
    function2() {
      console.log('function2 called')
    },
  },
}
</script>

Child.vue

<template>
  <button @click="emitPlease">please do emit for id {{ id }}</button>
</template>

<script>
export default {
  props: {
    id: {
      type: Number,
      default: 1,
    },
  },
  methods: {
    emitPlease() {
      this.$emit('picture-taken', this.id)
    },
  },
}
</script>

【讨论】:

  • 它不起作用。我开始想到我正在使用的 vue/nuxt 版本的一些错误或问题。它似乎没有正确传递任何道具。在“孩子”中,道具 this.id 始终为“1”。
  • @sangio90 我与您联系的内容正在运行,并通过了 id 12。你可能有一个错字或类似的东西。请仔细检查您的代码。
  • 这是我的错,但不是那么容易找到。事实证明,在组件内部有一个具有固定 id 的 ,所以我有 2 个具有相同 id 的输入,因此是随机行为。现在它可以完美地与我的第一个示例中的代码一起工作。非常感谢您的宝贵时间:-)
猜你喜欢
  • 2019-12-15
  • 1970-01-01
  • 2016-06-29
  • 2018-11-16
  • 2019-10-03
  • 2019-03-12
  • 2019-08-11
  • 2015-05-24
  • 1970-01-01
相关资源
最近更新 更多