首頁  >  問答  >  主體

javascript - 請問一下元件的生命週期beforeDestory是在什麼情況下面觸發的呢?

進行路由跳轉的時候能觸發嗎?我發現我進行路由跳轉的時候沒有觸發beforeDestory裡面的函數,但是有段程式碼需要在元件銷毀之前執行,請問我該怎麼做呢?
https://jsfiddle.net/44w37p34/ 剛剛有個朋友給我發了一個demo,我發現他的beforeDestory在路由跳轉的時候觸發了,但是我的一直都不行,請問是什麼原因呢

天蓬老师天蓬老师2637 天前1156

全部回覆(2)我來回復

  • 漂亮男人

    漂亮男人2017-07-05 10:48:40

    找到原因了,之前給router-view加了個keep-alive導致元件快取了,所以不會觸發beforeDestory和destoryed

    回覆
    0
  • 習慣沉默

    習慣沉默2017-07-05 10:48:40

    我試了一下,切換路由的時候能觸發執行beforeDestroy方法,範例如下。

    const Home = {
            template: `
          <p>
          <p class="section">Some section foo</p>
          <p class="section">Some section foo</p>
          <p class="section">Some section foo</p>
          <p class="section">Some section foo</p>
        </p>
      `,
            mounted() {
               console.log("Home mounted");
            },
            beforeDestroy() {
                console.log("Home destroy");
            }
        };
    
        const Test = {
            template: `
                <p>
                  <p class="section">Some section test</p>
                  <p class="section">Some section test</p>
                  <p class="section">Some section test</p>
                  <p class="section">Some section test</p>
                </p>
      `,
            mounted() {
                console.log("Test mounted");
            },
            beforeDestroy() {
                console.log("Test destroy");
            }
        };

    回覆
    0
  • 取消回覆