Does the 'destroyed' method in Vue get triggered when the page is refreshed?

I was curious to know if refreshing a page with a running Vue app would prompt the Vue's .destroyed callback.

After observing a Vue app that consists of these basic lifecycle callbacks:

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

only 'created' gets logged (not 'destroyed'). How can I verify if the .destroyed callback has been triggered?

Answer №1

I came across a similar query and solution on stackoverflow

How to execute code before page reload or close in vue.js

The user explains that nothing gets destroyed during a page reload, and provides the following code snippet:

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

To perform actions before a page refresh, you can use this approach.

Answer №2

Upon examining your query

Does Vue's 'destroyed' method get invoked when the page is refreshed?

No, the destroyed method is triggered if your component's controller is lost or manually destroyed, as demonstrated in the example above.

I came across a useful example in the vuejs forum that utilizes the external use of 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 Link

Here's another scenario. The destroy method will be called for a component if its control is lost or if it is removed

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

JavaScript Proxies: no activation of 'set' when making changes to objects within an array

I am working with an array that is filled with objects let objectArray = [{ id: 1, name: "John" }, { id: 2, name: "Bill" }, { id: 3, name: "Mike" }]; Next, I create a proxy with a set handler using my array as the target let proxy = new Prox ...

ng-repeat to prevent duplicate items from displaying

I intentionally have duplicates in my array of items and I am looking for a way to hide just one of them when clicked within my ng-repeat. Is there a way to hide only one of the duplicated items on click? I feel like I might be overlooking something, as ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...

Reflections on Javascript MVC Architecture

Here is my design of MVC utilizing JavaScript. I made a conscious effort to avoid using any MVC frameworks to achieve a clear structure and decoupled organization. What are your thoughts on my approach? I am considering incorporating something like requir ...

Certain URLs do not receive requests when using jQuery.ajax(), while others are successful

Our Rails application features inline editing, allowing users to submit changes back to the server via PUT requests. The URL for the PUT request varies based on the object being edited and the page the user is on. The same JavaScript code supports this fea ...

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

Picking the juiciest data from specific dates with MongoDB

I have a large amount of hourly recorded price data that I am organizing in mongodb, and I have a specific requirement to extract the value/price of an item within certain time intervals like 1 day, 1 week, 1 month, 3 months, and so on. The data is stored ...

Is there a way to simulate a virtual keyboard event (specifically the tab key) using Javascript in Internet Explorer 8

I'm looking to create a virtual keyboard event for tab using JavaScript. I've researched this topic and found some helpful answers, but I haven't been able to get it working properly. I know that JavaScript is an event-driven language and ty ...

Is it possible to exchange meshes across different scenes in three.js?

Can meshes or geometry be shared across scenes? I am facing an issue where I have multiple scenes that require the same large meshes, but attempting to share these meshes between scenes results in WebGL context errors. It seems like certain variables are ...

Can an FAQ accordion collapse the selected element when another element is clicked?

I recently started working on a FAQ accordion project from frontendmentor. The functionality works perfectly when clicking on a question to reveal the answer and clicking again to hide it. However, I am facing an issue where if I click on one question and ...

Retrieving various sets of JSON objects arrays

I have successfully stored an array of JSON objects in the database using the following code: function send_custom_markers() { var reponse = confirm("Send markers to selected contacts?"); if (reponse === true) { var json_markers = new ...

Creating an HTTP interceptor in Backbone: A step-by-step guide

After gaining experience with backbone, I decided to delve into learning angular. The features of angular really caught my interest, especially the HTTP interceptor. I began thinking about how to implement this functionality in backbone to display a spin ...

Load HTML/erb templates efficiently in Rails to optimize performance for AngularJS applications

I recently came across a discussion about eager loading HAML templates on this website. The concept of caching HTML partials to enhance performance in Angular applications caught my attention. However, I'm curious to know if there is a similar approac ...

Retrieving the value associated with a specific key in Vue.js

When it comes to Vue.js, I am trying to figure out how to access the value of a key. My goal is to use the key as an id and then access the title using something like key.title. Below is the code snippet that I have been experimenting with: HTML <ul ...

What is the best method to host my Vuejs frontend files using my node/express server?

Currently, I am configuring two routes in Express - one for the home page and the other for the admin page. However, I am struggling to find comprehensive documentation on integrating Vuejs with Express in a way that allows me to serve both pages simulta ...

Pass the array as a parameter for deleting users in the route

In order to delete one or more users using the method destroy, I need to pass an array of values to be deleted: public function destroy(Request $request) { // DB::table('users')->whereIn('id', $request->user)-& ...

The Vue application coupled with a Node backend fails to display any content other than the homepage when running on a Windows localhost. However, it functions properly on a MacOS

After successfully running the app in production on MacOS localhost for a year, the need arose to configure the app to run on Windows 10 localhost. Despite fixing all errors, the app now boots up on Windows, requests go through, but only the '/' ...

Interested in creating a weather application that changes color based on the time of day

My attempt to create a weather app with a glowing effect has hit a roadblock. I want the app to glow "yellow" between 6 and 16 hours, and "purple" outside of those hours. I have assigned classes for AM and PM elements in HTML, and styled them accordingly i ...