:::

5-1 子組件→父組件間的參數傳遞(emits)

  1. 子組件:倒數計時組件,預設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>
    1. 可以先在 emits:{} 中定義要傳什麼東西到父組件(沒設也行),也就是要送到父組件的函式,可以在裡面做參數的驗證。
    2. setup(props, { emit }) {} 中從 context 解構出 emit 功能,並在掛載後將 TimeOut 函數及 num 值透過 emit 傳送到父組件
  2. 父組件
    <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>
    
    1. 當子組件將 TimeOut 函數及 numemit 到父組件時,就會觸發 <TimerBox @TimeOut ="handleTimeOut" /> 中的 @TimeOut事件,同時會執行 handleTimeOut 函式
    2. 父組件要在 setup(){} 中定義好 handleTimeOut 函式的內容並 return 出來

實際範例:


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D33%26tbdsn%3D1738

計數器

今天: 2109210921092109
昨天: 3176317631763176
總計: 7451541745154174515417451541745154174515417451541