vue 3 发出警告“无关的非发射事件侦听器”

Fan*_*119 33 javascript eventemitter vue.js vuejs3 vue-composition-api

我正在尝试使用组合 API 将数据从子级发送到父级

我收到以下警告。

[Vue 警告]:无关的非发射事件侦听器 (updatedcount) 已传递给组件,但无法自动继承,因为组件呈现片段或文本根节点。如果侦听器仅用作组件自定义事件侦听器,请使用“发射”选项声明它。at <HelloWorld onUpdatedcount=fn > at

子组件.vue


<template>
  <h1>{{ store.count }}</h1>
  <button @click="fired">click me</button>
</template>

<script>
import useStore from "../store/store.js";
export default {
  name: "HelloWorld",
  setup(_,{ emit }) {
    const store = useStore();

    const fired = () => {
      store.count++;
      emit("updatedcount", store.count);
    };

    return {
      store,
      fired
    };
  },
};
</script>


Run Code Online (Sandbox Code Playgroud)

父组件.vue


<template>
  <div>
    {{ hello }}
    <br />
    <br />
    <input type="text" v-model="hello.searchQuery" />
    <br><br>
    <button @click="hello.count--">click me too!</button>
    <hello-world @updatedcount="mydata" />
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import useStore from "./store/store.js";

export default {
  components: {
    HelloWorld,
  },
  setup() {
    const hello = useStore();

    function mydata(event) {
      console.log(event);
    }

    return {
      hello,
      mydata
    };
  },
};
</script>

Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 38

我认为你需要emits在你的组件中定义:https : //v3.vuejs.org/guide/component-custom-events.html#defining-custom-events

export default {
  name: "HelloWorld",
  emits: ["updatedcount"], // <--- add this line
  setup(_,{ emit }) {
    ...
  },
};
Run Code Online (Sandbox Code Playgroud)

  • 请注意,现在最好按照您的方式命名事件 - 没有连字符,只有小写字母。如果您将其命名为 kebab-case,运行时会抱怨您没有将其声明为以驼峰命名法形式发出;另一方面,如果您将其命名为驼峰命名法,EsLint 会抱怨,因为事件应该是短横线命名法。 (5认同)
  • 感谢宇宙的创造者创造了 SoF,让好人能够发布如此好的答案。 (2认同)

小智 25

当我在自己的 vue 3 应用程序中看到此错误时,我发现将组件的模板内容包装在空 div 中可以解决我的问题,我认为这与错误消息的“无法自动继承”部分有关。

vue 的工作方式似乎是,vue 将尝试对 @click 和 @input 等常见事件使用属性继承来传递给底层元素,但是当组件的根目录中有多个同级元素时,它不知道该传递哪一个选择。

请注意,这些事件可能会更改某些行为,因为新的包装父 div 现在将有直接与其关联的事件。

<template>
  <div>
    <h1>{{ store.count }}</h1>
    <button @click="fired">click me</button>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)


Fan*_*119 20

更新:

在 vue 3 脚本设置中你会做

const emits = defineEmits(["updatedcount"])

emits("updatedcount", store.count);
Run Code Online (Sandbox Code Playgroud)