我正在尝试使用合成API从子级向父级发送数据
我收到以下警告。
[Vue警告]:无关的非发出事件侦听器(updatedcount)已传递给组件,但由于组件呈现片段或文本根节点,因此无法自动继承。如果侦听器仅打算用作组件自定义事件侦听器,请使用“ emits”选项声明它。在
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>
答案 0 :(得分:8)
我认为您需要在组件中定义emits
:https://v3.vuejs.org/guide/component-custom-events.html#defining-custom-events
export default {
name: "HelloWorld",
emits: ["updatedcount"],// this line
setup(_,{ emit }) {
const store = useStore();
const fired = () => {
store.count++;
emit("updatedcount", store.count);
};
return {
store,
fired
};
},
};
根据文档,您甚至可以通过检查参数是否可用来验证事件。