一、组件通信
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>