vue 3发出警告“外部非事件侦听器”

8qgya5xd  于 2022-11-25  发布在  Vue.js
关注(0)|答案(4)|浏览(274)

我正在尝试使用合成API将数据从子对象发送到父对象
我收到以下警告。
[Vue警告]:已将外部的非发出事件侦听器(updatecount)传递给组件,但无法自动继承,因为组件呈现片段或文本根节点。如果侦听器仅用作组件自定义事件侦听器,请使用“emites”option.at〈HelloWorld onUpdatedcount=fn〉声明它
childcomponent.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>

parentcomponent.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>
nhhxz33t

nhhxz33t1#

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

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

but5z9lq2#

更新:
在vue 3脚本设置中,您将执行以下操作

const emits = defineEmits(["updatedcount"])

emits("updatedcount", store.count);
n1bvdmb6

n1bvdmb63#

当我在自己的vue 3应用程序中看到这个错误时,我发现将组件的模板内容 Package 在一个空div中可以解决这个问题,我相信这与错误消息中的“无法自动继承”部分有关。
看起来vue的工作方式是,vue将尝试对常见事件(如@click和@input)使用属性继承,以传递给底层元素,但当组件的根有多个同级元素时,它不知道选择哪一个。
请注意,这些事件可能会改变某些行为,因为新的 Package 父div现在将有事件直接绑定到它。

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

a11xaf1n4#

在vue3中,您必须定义发射,子元件如下所示:
childcomponent.vue:

<template>
      <h1>{{ store.count }}</h1>
      <button @click="fired">click me</button>
    </template>
    
    <script>
    import useStore from "../store/store.js";
    export default {
      name: "HelloWorld",
      emits :{
          updatedcount: null,
        },
      data: () => ({
            store: useStore(),
      }),
      methods:
        fire () {
          store.count++;
          this.$emit("updatedcount", store.count);
        },
      
    };
    </script>

相关问题