Vue3 父組件調用子組件的方法


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調用子組件方法

vue2調用子組件方法

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM