父组件: 核心就是
@custom-event,通过这个绑定到了子组件提交的方法
<template><div><p>接收的数据: {{ receivedData }}</p><Demo4Chiren2 @custom-event="handleGetWeb" /></div>
</template><script>
import { ref } from 'vue';
import Demo4Chiren2 from './demo4Chiren2.vue';export default {components: { Demo4Chiren2 },setup() {const receivedData = ref(null);const handleGetWeb = (data) => {console.log(data); // 这里打印接收到的数据receivedData.value = data;};return {handleGetWeb, receivedData};}
}
</script>
子组件
记住一定要在setup哪里标上{emit},不然要报错,我搞了半天才晓得。很奇怪的一点,我看别人视频上,就没写{emit}就可以用,但是我为什么要
<template><div><button @click="sendData">发送数据</button></div>
</template><script>
import { defineComponent } from 'vue';export default defineComponent({setup(props, { emit }) {const sendData = () => {const data = { message: 'Hello from Demo4Chiren2' };emit('custom-event', data);};return { sendData };}
});
</script>
不通过按钮去上传数据,不用定义一个方法去就行了,直接 emit('custom-event', data);
<template><div>
<!-- <button @click="sendData">发送数据</button>--><h1>子数据</h1></div>
</template><script>
import { defineComponent, ref } from 'vue';export default defineComponent({setup(props, { emit }) {// 子组件通过自定义事件,发送数据,父组件要去接受数据emit('begin','zzzzz')// const sendData = () => {// const data = {message: 'Hello from Demo4Chiren2'};// emit('custom-event', data);// };const exposedData = ref("我是子暴露的数据");const sayHi = () => {return "我是子暴露的方法被调用返回的结果";};return { exposedData, sayHi};},expose: ['exposedData', 'sayHi']
});
</script>
vue3中setup函数子传父普通写法,子暴露,以及自己踩过的坑
子组件:一定要return,还有它暴漏的方式还不一样。
<template><div><button @click="sendData">发送数据</button></div>
</template><script>
import { defineComponent, ref } from 'vue';export default defineComponent({setup(props, { emit }) {const sendData = () => {const data = {message: 'Hello from Demo4Chiren2'};emit('custom-event', data);};const exposedData = ref("我是子暴露的数据");const sayHi = () => {return "我是子暴露的方法被调用返回的结果";};return {sendData, exposedData, sayHi};},expose: ['exposedData', 'sayHi']
});
</script>
父组件
<template><div><h1>父组件</h1><Demo4Chiren2 @custom-event="handleCustomEvent" ref="demoChild" /><button @click="callChildMethod">调用子组件方法</button><p>子组件数据: {{ childData }}</p></div>
</template><script>
import { defineComponent, ref } from 'vue';
import Demo4Chiren2 from './Demo4Chiren2.vue'; // 请根据实际路径调整export default defineComponent({components: {Demo4Chiren2},setup() {const demoChild = ref(null);const childData = ref('');const handleCustomEvent = (data) => {console.log('接收到子组件数据:', data);childData.value = data.message;};const callChildMethod = () => {if (demoChild.value) {console.log(demoChild.value.sayHi());}};return {demoChild,childData,handleCustomEvent,callChildMethod};}
});
</script>