Home  >  Q&A  >  body text

javascript - Under what circumstances is the component's life cycle beforeDestory triggered?

Can it be triggered when routing a jump? I found that the function in beforeDestory was not triggered when I made a route jump, but there was a piece of code that needed to be executed before the component was destroyed. What should I do?
https://jsfiddle.net/44w37p34/ A friend just sent me a demo. I found that his beforeDestory was triggered when the route jumped, but mine never worked. What is the reason?

天蓬老师天蓬老师2686 days ago1187

reply all(2)I'll reply

  • 漂亮男人

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

    I found the reason. I added a keep-alive to the router-view before, causing the component to be cached, so beforeDestory and destoryed will not be triggered

    reply
    0
  • 習慣沉默

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

    I tried it, and it can trigger the execution of the beforeDestroy method when switching routes. The example is as follows.

    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");
            }
        };

    reply
    0
  • Cancelreply