user7693832
user7693832

Reputation: 6849

Is Vue's 'destroyed' method called on page refresh?

I am wondering if refreshing a page that runs a Vue app will trigger the Vue's .destroyed callback.

From what I observed in a Vue app that contains these simple lifecycle callbacks:

created() {
  console.log(' created');
},
destroyed() {
  console.log('destroyed');
}

only 'created' is logged (not 'destroyed'). How can I check if the .destroyed callback has been executed?

Upvotes: 5

Views: 32147

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

As your question was

Is Vue's 'destroyed' method called on page refresh?

No, destroyed method called if your component's controller lost or you manually destroy, above example is for manually destroy.

I have found very good example in vuejs forum which uses externally this.$destroy() method.

new Vue({
  el: '#app',
  data() {
    return {
      value: 'will work until destroy'
    };
  },
  methods: {
    destroy() {
      this.$destroy();
    }
  },
  beforeDestroy() {
    console.log('Main Vue destroyed')
  }
})

var tmp = Vue.extend({
  template: `
  	<div>
      <span>{{ value }}</span>
      <input v-model="value" />
    </div>
  `,
  data() {
    return {
      value: 'always bind and work'
    };
  },
  beforeDestroy() {
    console.log('Mounted destroyed')
  }
});

new tmp().$mount('#mount-point');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
  {{ value }}
  <input v-model="value" />
  <div id="mount-point"></div>
  <button @click="destroy()">Destroy</button>
</div>

Reference

Another example. If component's control lost or removed then destroy method will be called of that component's

Vue.component('comp1', {
  template: '<div>A custom component1!</div>',
  destroyed(){
    console.log('comp1 destroyed');
  }
})

Vue.component('comp2', {
  template: '<div>A custom component2!</div>',
  destroyed(){
    console.log('comp2 destroyed');
  }
})

new Vue({
  el: '#app',
  data() {
    return {
      value: 1
    };
  },
  methods: {
  },
  beforeDestroy() {
    console.log('Main Vue destroyed')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
  <select v-model="value">
    <option value="1">comp1</option>
    <option value="2">comp2</option>
  </select>
  <comp1 v-if="value==1"></comp1>
   <comp2 v-if="value==2"></comp2>
  <button @click="destroy()">Destroy</button>
</div>

Upvotes: 1

onuriltan
onuriltan

Reputation: 3908

I found the similar question and answer to it on stackoverflow

Do something before reload or close in vue.js

He/she basically explains that nothing is destroyed on page reload, you need to define

window.onbeforeunload = function(){
  return "Are you sure you want to close the window?";
}

If you want to do something before a page refresh

Upvotes: 8

Related Questions