猿问

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

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


我收到以下警告。


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



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


繁星淼淼
浏览 230回答 4
4回答

心有法竹

我认为您需要emits在组件中定义:export default {  name: "HelloWorld",  emits: ["updatedcount"], // <--- add this line  setup(_,{ emit }) {    ...  },};

沧海一幻觉

更新:在 vue 3 脚本设置中你会做const emits = defineEmits(["updatedcount"])emits("updatedcount", store.count);

牛魔王的故事

当在我自己的 vue 3 应用程序中看到此错误时,我发现将组件的模板内容包装在一个空的 div 中可以解决我认为与错误消息的“无法自动继承”部分有关的问题。似乎 vue 的工作方式是 vue 将尝试对 @click 和 @input 等常见事件使用属性继承以传递给底层元素,但是当组件的根部有多个同级元素时,它不知道要传递哪个选择。请注意,这些事件可能会改变某些行为,因为新的包装父 div 现在将直接绑定到它的事件。<template>&nbsp; <div>&nbsp; &nbsp; <h1>{{ store.count }}</h1>&nbsp; &nbsp; <button @click="fired">click me</button>&nbsp; </div></template>

慕虎7371278

在 vue3 中你必须定义 emits,你的子组件看起来像这样:子组件.vue:&nbsp; &nbsp; <template>&nbsp; &nbsp; &nbsp; <h1>{{ store.count }}</h1>&nbsp; &nbsp; &nbsp; <button @click="fired">click me</button>&nbsp; &nbsp; </template>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <script>&nbsp; &nbsp; import useStore from "../store/store.js";&nbsp; &nbsp; export default {&nbsp; &nbsp; &nbsp; name: "HelloWorld",&nbsp; &nbsp; &nbsp; emits :{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; updatedcount: null, <--- add this lines&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; data: () => ({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; store: useStore(),&nbsp; &nbsp; &nbsp; }),&nbsp; &nbsp; &nbsp; methods:&nbsp; &nbsp; &nbsp; &nbsp; fire () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; store.count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.$emit("updatedcount", store.count);&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; };&nbsp; &nbsp; </script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答