vue3进阶

一、组件通信

1 props 父传子

父组件传值

<template>
<Child name="张三" :age="20" :gender="gender"></Child>
</template>

<script setup lang="ts">
    import { ref } from 'vue';
    import Child from './Child.vue';
    const gender = ref('男');
</script>

子组件接收值

<template>
<h1>子组件</h1>
<h2>{{ name }}</h2>
<h2>{{ age }}</h2>
<h2>{{ gender }}</h2>
</template>

<script setup lang="ts">
    
    const props = defineProps<{
        name: string,
        age: number,
        gender: string
    }>()

    console.log(props.age);

</script>

2 emit子传父-回调函数-闭包利用

1、绑定自定义事件

<template>
    <Child @getChildData="getChildData"></Child>
</template>

<script setup lang="ts">

const getChildData = (data: any) => {
    console.log('子组件传递的数据', data);
}
</script>

2、子组件触发自定义事件

<template>
    <h1>子组件</h1>
    <button @click="dataToFather">传值</button>
</template>

<script setup lang="ts">
const emit = defineEmits(['getChildData'])
const dataToFather = () => {
    emit('getChildData', 'hello');
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值