Vue3 父組件調用子組件的方法
// 父組件 <template> <div>
父頁面 <son-com ref="sonRef"/> <button @click="handleClick">test</button> </div> </template> <script> import { defineComponent, ref, } from 'vue'; export default defineComponent({ setup(){
const sonRef = ref(null); const handleClick = () => { sonRef.value.song(); }
return { sonRef, handleClick, }
}
})
</script>
// 子組件
<template>
<div> 子頁面 </div> </template> <script> import { defineComponent } from 'vue'; export default defineComponent({ setup(){
const song = () => alert('hello world');
return {
song, // 別忘記 return
}
}
})
</script>
如果是TS定義可以使用
const sonRef = ref<null | HTMLElement>(null);
vue2調用子組件方法