008Vue3语法糖defineProps、defineEmits、defineExpose
获取组件传值defineProps
defineProps<{
msg: string;
num?: number;
}>();
interface Props {
msg?: string;
labels?: string[];
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two'],
});
defineProps({
msg: String,
num: {
type: Number,
default: '',
},
});
子组件向父组件事件传递defineEmits
const emit = defineEmits<{ (e: 'click', num: number): void }>();
const emit = defineEmits(['click']);
const clickThis = () => {
emit('click', 2);
};
组件暴露自己的属性defineExpose
<template>
<div>子组件{{ count }}</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const count = ref(123456);
const add = (a: number, b: number): number => {
return a + b;
};
defineExpose({
add,
count,
});
</script>
<template>
<div @click="helloClick">父组件</div>
<div @click="add(8, 9)">add</div>
<TestChild ref="hello"></TestChild>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import TestChild from './TestChild.vue';
const hello = ref<any>(null);
const helloClick = () => {
console.log(hello?.value?.count);
};
const add = (a: number, b: number): number => {
console.log(666.333, hello, hello?.value?.add(5, 6));
return hello?.value?.add(a, b);
};
</script>