How to Reload a Page or Component in Vue/Nuxt JS

In order to refresh a Vue component and have the hooks executed properly, it must be in the eyes of Vue destroyed and created again.

For this there is a property called "key" that is executed internally and/or manually in the framework to recognize each of the Vue components, which is mandatory when creating a list of elements, being similar to an ID for the component.

Next, I will show you an example in which by adding and modifying the "key" attribute we can reconstruct and re-execute all the life hooks of the component.

<template> <main> <my-component :key="key" /> <button @click="refresh">refresh</button> </main> </template> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ data() { return { key: 1 } }, methods: { refresh() { this.key++ } } }) </script>
Refresh Parent Component
<template> <div> <span>Refresh Component</span> </div> </template> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ created() { alert('component refreshed') } }) </script>
Refresh Child Component

Important

For the component rebuild to run correctly, the "key" must be assigned in the parent component and not in the child component.

Next, there is an example that will NOT refresh the component.

<template> <!-- it not works, because the "key" is a simple attribute --> <main :key="key"> <button @click="refresh">refresh</button> </main> </template> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ data() { return { key: 1 } }, created() { alert('component refreshed') }, methods: { refresh() { this.key++ } } }) </script>
Component with a Bad Refresh Implementation

As you can see, the key is initialized from the component to be refreshed, so Vue will not understand that it is the "key" that is used to differentiate each component, but rather a normal attribute of the tag.