vue3父子组件Emits、props、defineExpose

//父组件

<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
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值