【问题标题】:vue 3 emit warning " Extraneous non-emits event listeners"vue 3 发出警告“无关的非发射事件侦听器”
【发布时间】:2021-01-21 00:49:27
【问题描述】:

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

我收到以下警告。

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


父组件.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>

【问题讨论】:

    标签: javascript vue.js eventemitter vuejs3 vue-composition-api


    【解决方案1】:

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

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

    【讨论】:

    • @Fanna1119 我也花了一段时间才重新找到它,所以不要自责;)
    • 请注意,现在最好按照您的方式命名事件 - 没有连字符,只有小写字母。如果您将其命名为 kebab-case,运行时会抱怨您没有在 camelCase 中将其声明为发出;另一方面,如果你把它命名为 camelCase,EsLint 会抱怨,因为事件应该是 kebab-case。
    • 感谢宇宙的创造者创造了 SoF,让好人可以发布这么好的答案。
    • 它对我有用。谢谢
    猜你喜欢
    • 2021-03-04
    • 2017-10-19
    • 2021-02-03
    • 2016-07-06
    • 2020-09-06
    • 2013-05-13
    • 2015-12-18
    • 1970-01-01
    • 2013-05-19
    相关资源
    最近更新 更多