setup函数子传父普通写法

发布于:2024-09-17 ⋅ 阅读:(131) ⋅ 点赞:(0)

父组件

<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>

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>


网站公告

今日签到

点亮在社区的每一天
去签到