在Vue 3中,子组件可以使用$emit方法向父组件传递事件,父组件通过监听这些事件来接收子组件的信息。以下是三种常见的子传父通信方法:
1.使用v-on或@监听子组件事件:
<!-- 父组件 -->
<template>
<ChildComponent @child-event="parentMethod" />
</template>
<script>
import { defineComponent } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default defineComponent({
components: {
ChildComponent
},
setup() {
const parentMethod = (payload) => {
console.log('Received from child:', payload);
};
return {
parentMethod
};
}
});
</script>
<!-- 子组件 -->2.使用ref和toRefs绑定子组件的方法:
<template>
<button @click="emitEvent">Click me</button>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
setup(props, { emit }) {
const emitEvent = () => {
emit('child-event', 'some data');
};
return {
emitEvent
};
}
});
</script>
<!-- 父组件 -->
<template>
<ChildComponent ref="childComp" />
</template>
<script>
import { defineComponent, ref, onMounted } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default defineComponent({
components: {
ChildComponent
},
setup() {
const childComp = ref(null);
onMounted(() => {
childComp.value.parentMethod('some data');
});
return {
childComp
};
}
});
</script>
<!-- 子组件 -->3.使用provide和inject:
<template>
<div>{{ message }}</div>
</template>
<script>
import { defineComponent, reactive, toRefs } from 'vue';
export default defineComponent({
setup(props, { emit }) {
const state = reactive({
message: 'Hello from child',
});
const parentMethod = (data) => {
state.message = `Received from parent: ${data}`;
};
return {
...toRefs(state),
parentMethod
};
}
});
</script>
<!-- 父组件 -->
<template>
<ChildComponent />
</template>
<script>
import { provide } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
provide('parentMsg', 'Hello from parent');
}
};
</script>
<!-- 子组件 -->
<template>
<div>{{ parentMsg }}</div>
</template>
<script>
import { inject } from 'vue';
export default {
setup() {
const parentMsg = inject('parentMsg');
return {
parentMsg
};
}
};
</script>
- 本文标题: vue3子传父三种方法
- 文章分类:【VueJS】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.