//父组件
<Test2 :title="title" :list="list"
@parentClick="parentClick"
@parentChange="parentChange"
@parentCount="parentCount"
ref="test2Ref"
></Test2>
const test2Ref = ref<{count2:number,way:()=>void} | null>(null)
onMounted(()=>{
console.log(test2Ref.value?.count2,'2');
console.log(test2Ref.value?.way(5),'10');
})
//下面三个是接收子传父的方法
const count = ref(1)
const parentClick = (v:number)=>{
// alert('子组件触发了父组件的 parentClick')
count.value += v;
}
const parentChange = ()=>{
alert('子组件触发了父组件的 parentChange')
}
const count2 = ref<number | null>(null)
const parentCount = (v:number)=>{
count2.value = v
}
//子组件
//defineProps
const props = withDefaults(defineProps<{
title?:string, //因为可以不传有默认值所以?严谨一些
list:List[],
}>(),{
title:'默认'
})
//defineEmits
const emits = defineEmits<{
(e:'parentClick',data:number):void,
(e:'parentChange'):void,
(e: "info", voice: HTMLMediaElement): void;
}>();
const handleClick =()=>{
emits('parentClick',2)
emit("info", voice.value as HTMLMediaElement);
}
console.log(props.title,'title');
const count2 = ref<number>(2)
const way=(v:number)=>{
return 2*v
}
//如果子组件是setup,父组件ref调用子组件方法子组件要用defineExpose暴露
defineExpose({ //暴露子组件的数据
count2,
way
})