Vue3组件传参之父子组件传参

在Vue3中,父子组件之间的通信是一项常见的任务。本文将介绍一些在Vue3中实现父子组件之间传值的方法。

一、Props(父组件向子组件传参)

在Vue3中,可以使用props来在父组件向子组件传递数据。在父组件中,可以通过在子组件上使用v-bind指令,将数据绑定到子组件的defineProps方法上。子组件可以直接通过defineProps里的属性访问到传递过来的数据。

// ParentComponent.vue
<template>
  <div>
    <ChildComponent :arrList="arrList" :message="message" />
  </div>
</template>

<script setup lang="ts">
    import ChildComponent from "../ChildComponent/ChildComponent.vue";
    import { ref, reactive } from "vue";
    const message = ref<string>("Hello from parent component!");
    const arrList = reactive([1, 2, 3]);
</script>


// ChildComponent.vue
<template>
  <div>
    {{ message }}
    {{ arrList }}
  </div>
</template>

<script setup lang="ts">
    import { ref, reactive } from "vue";
    interface Iprops {
        message?: string;
        arrList?: number[];
    }
    const props = withDefaults(defineProps<Iprops>(), {
        arrList: [888],
    });

    console.log(props.message);
</script>
<style scoped></style>


在上面的例子中,父组件通过props将名为message的数据传递给子组件,并在子组件中显示。在子组件中,可以使用 withDefaults的第二个参数来定义默认值

二、defineEmits 子组件向父组件传参

除了父组件向子组件传递数据,子组件也可以向父组件传递数据。Vue3中可以使用defineEmits方法来触发自定义事件,并将数据作为参数传递给父组件。

// ParentComponent.vue
<template>
  <div>
    <ChildComponent @send-message="sendMessage" />
  </div>
</template>

<script setup lang="ts">
	import ChildComponent from "../ChildComponent/ChildComponent.vue";
	const sendMessage= (val) => {
  		console.log(val); //Hello from child component!
	};
</script>


// ChildComponent.vue
<template>
    <div @click="handleClick">向父组件传参</div>
</template>

<script setup lang="ts">
    const $emit = defineEmits<{
        (e: "send-message", data: any): void;
    }>();
    const handleClick = () => {
        $emit("send-message", "Hello from child component!");
    };
</script>



在上面的例子中,子组件通过点击按钮触发handleClick 方法,并使用$emit方法传递一个名为send-message的自定义事件,同时传递了一个字符串作为参数。父组件通过监听该自定义事件,获取到子组件传过来的值

三、defineExpose 父组件直接获取子组件的值

// ParentComponent.vue
<template>
  <div>
    <ChildComponent ref="refChild" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import ChildComponent from "../ChildComponent/ChildComponent.vue";
const refChild = ref<InstanceType<typeof ChildComponent>>(null);
onMounted(() => {
  console.log(refChild.value.msg); // 子组件的数据
});
</script>
<style scoped></style>


// ChildComponent.vue
<template>
  <div>向父组件传参</div>
</template>

<script setup lang="ts">
import { ref } from "vue";
defineExpose({
  msg: "子组件的数据",
});
</script>
<style scoped></style>


在上面的例子中,子组件通过defineExpose方法暴露出自己的参数,父组件通过ref方式进行获取。指的注意的是,获取子组件数据需要在onMounted中获取,否则获取不到

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值