Vue 3子组件$emit事件未触发父组件方法,求排查与解决方案
解决Vue 3中子组件$emit未触发父组件事件的问题
我仔细梳理了你的代码,发现几个关键问题导致emit事件没被正确捕获,咱们一步步来修正:
1. 模板语法错误
父组件模板里的 < Child 有多余空格,Vue无法正确识别这个组件标签,必须改成 <Child(去掉标签名前的空格):
<template> <First/> <Child v-bind:sample="sample" @enlarge-text="onEnlargeText"/> </template>
2. TypeScript接口定义错误
子组件里你定义了 SampleInterface,但data返回的类型写的是 AddInterface——这个接口根本不存在,会导致TypeScript编译报错,进而影响组件正常运行。修正接口名称:
interface AddInterface { text: string; error: string; }
3. (可选)优化组件命名一致性
你的子组件name是 Add,但父组件里注册和引用的是 Child,这本身不影响功能,但为了代码可读性,建议保持组件名和引用名一致,比如把父组件里的 import Child from './Child.vue'; 改成 import Add from './Child.vue';,然后components里注册 Add,模板里用 <Add>,避免后续混淆。
修正后的完整代码
父组件(Container.vue)
<template> <First/> <Child :sample="sample" @enlarge-text="onEnlargeText"/> </template> <script lang="ts"> import { defineComponent } from 'vue'; import axios from 'axios'; import First from './First.vue'; import Child from './Child.vue'; export default defineComponent({ name: 'Container', components: { First, Child }, methods: { onEnlargeText() { console.log('enlargeText'); }, }, data: () => ({ sample: [], parentmessage: '', }), created() { axios.get('http://localhost:8080/getData') .then((response) => { console.log(response); this.sample = response.data; }) .catch((error) => { console.log(error); }); }, }); </script>
子组件(Child.vue)
<template> <div id="add"> <form id="signup-form" @submit.prevent="submit"> <label for="text">Text:</label> <input type="text" v-model="text" required> <p class="error">{{ error }}</p> <div class="field has-text-right"> <button type="submit" class="button is-danger">Submit</button> </div> </form> <button @click="tryThis"> Enlarge text </button> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; import axios from 'axios'; interface AddInterface { text: string; error: string; } export default defineComponent({ name: 'Add', // 建议声明要触发的事件,提升代码可读性和类型检查 emits: ['enlarge-text'], data: (): AddInterface => ({ text: '', error: '', }), methods: { tryThis() { this.$emit('enlarge-text'); }, submit() { this.$emit('enlarge-text'); }, }, }); </script>
关于Vue 3中$emit的使用
完全可以继续使用 this.$emit!在Vue 3的选项式API里,$emit 的用法和Vue 2完全一致;如果是组合式API(
相关产品推荐
相关产品推荐

