:::
5-1 子組件→父組件間的參數傳遞(emits)
- 子組件:倒數計時組件,預設5秒,0秒時停止
<script> import { onMounted, ref } from "vue"; export default { emits: { TimeOut: (num) => { return num.value === 0; }, }, setup(props, { emit }) { const num = ref(5); let timer = null; onMounted(() => { timer = setInterval(() => { num.value--; if (num.value === 0) { clearInterval(timer); emit("TimeOut", num); } }, 1000); }); return { num, }; }, }; </script> <template> <h1>{{ num }}</h1> </template> <style lang="scss" scoped> </style>- 可以先在
emits:{}中定義要傳什麼東西到父組件(沒設也行),也就是要送到父組件的函式,可以在裡面做參數的驗證。 - 在
setup(props, { emit }) {}中從context解構出emit功能,並在掛載後將TimeOut函數及num值透過emit傳送到父組件
- 可以先在
- 父組件
<script> import TimerBox from "@/components/TimerBox.vue"; export default { components: { TimerBox, }, setup() { const handleTimeOut = (num) => { if (num.value === 0) { console.log("時間到:", num.value); } }; return { handleTimeOut, }; }, }; </script> <template> <TimerBox @TimeOut="handleTimeOut" /> </template> <style> </style>- 當子組件將
TimeOut函數及num值emit到父組件時,就會觸發<TimerBox @TimeOut ="handleTimeOut" />中的@TimeOut事件,同時會執行handleTimeOut函式 - 父組件要在
setup(){}中定義好handleTimeOut函式的內容並return出來
- 當子組件將
實際範例:
5. 父組件→子組件間的參數傳遞(props)