Vue Keep-Alive - Component unable to maintain state between route transitions

After defining the main page of my vue app this way:

<div class="wrapper">
    <keep-alive>
      <app-header></app-header>
    </keep-alive>
    <router-view></router-view>
</div>

<script>
import appHeader from '../components/Header';

export default {
  components: {
    appHeader
  }
/* etc... */
}

I have a Dashboard UI with various routes and sub-route paths to display different pages. However, I want the app-header to remain at the top of all pages (components).

The issue arises when I click on any button that changes vue-router's route to another page, causing the app-header to be recreated (the created() lifecycle hook function is called).

I am puzzled by this behavior because I added keep-alive, expecting it to render only once. Any insights into why this is happening would be greatly appreciated.

I've searched extensively online for a solution but haven't been able to find one yet.

Thank you in advance for your assistance.

Answer №1

Using the keep-alive feature in Vue.js will only keep the section wrapped by the <keep-alive> tag alive. Specifically, in this example, the app-header component will be kept alive. To apply this to all components within the routes, you must place the <router-view> inside the <keep-alive> tag.

For example:

  <keep-alive>
    <router-view></router-view>
  </keep-alive>

By doing this, the keep-alive functionality will now work for all routes in your application.

Answer №2

Response provided by Rijosh is specifically for Vue 2 and its router (Router v3.x). For those using Vue 3 (and Router v4.x), the code for <keep-alive> and <router-view> will appear as follows:

<router-view v-slot="{ Component }">
   <keep-alive>
      <component :is="Component" />
   </keep-alive>
</router-view>

Additional information can be found in the documentation here.

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

Ways to transfer a variable from JavaScript/jQuery to Java

I am trying to access data retrieved from another server in a Java class using JavaScript/jQuery. The data I receive from the server as a post result to my servlet is in the form of a JSON String. The response looks like this: [{"id":"1","bool_m":"0","na ...

Dealing with the main directory/path in Express and Node JS

I've been working on my site using Express and Node JS, and I'm attempting to handle users' requests for 'www.mysite.com/' or 'www.mysite.com' by redirecting them to 'www.mysite.com/dashboard'. Is there a way to ...

The module 'react/jsx-runtime' could not be located within the path relative to '@mui/styled-engine/StyledEngineProvider/StyledEngineProvider.js'

I encountered this issue when attempting to create a new React project using MUI. I followed this code example from the documentation, which functions correctly in their live Codesandbox but not on my local setup. Here is the complete error message: Module ...

`The functionality of parent.location is not operating as expected in Firefox and Chrome, however, it is functioning

Issue with JSP: <A NAME="CustomerInformation"></A> <table class="SectionHeader1"> <TBODY>enter code here <tr> <td>Customer Information</td> </tr> </TBODY> </table ...

Uncertainty surrounding port configurations for web applications

My current project is well underway in development, but I'm facing an issue with the ports. The Client side is a single-page application built with backbone.js, utilizing Sails as a server. The problem lies in the fact that the Client is running on ...

Obtaining a File type object from a URL (specifically an image) in Vue.js

Suppose I have an image URL like http://localhost/sample.jpg. What is the best way to save this image URL into a File object using native JavaScript API in my component? export default { created () { const imageUrl = 'http://localhost/sample.jpg ...

Can a function be appropriately utilized in a reducer?

For my reducer, I am looking to incorporate a function that is necessary for sorting. I have successfully imported this function from another file and it seems to be functioning correctly. However, I am unsure about the validity of importing and using fu ...

The Express.js main router is functioning properly, however, the other routers connected to it are experiencing

I'm encountering an issue with my routers. The main route /weather is working fine, but other routes connected to it are not functioning properly. app.js const express = require('express'); const weatherRoute = require('./back/routes/w ...

A lesson is what I'm seeking, as I face an Uncaught TypeError: Unable to locate the property 'split' of an undefined value

Although this question has been asked multiple times before, I am a beginner and eager to learn. I would greatly appreciate it if someone could take the time to explain this to me. I have tried to find a solution to this error using the existing answers, b ...

In the realm of Laravel, Vue, and Javascript, one may question: what is the best approach to omitting a key

When working with JSON data, I encountered a problem where leaving some keys unfilled resulted in incorrect results. I want to find a way to skip these keys if they are not filled. I have shared my code for both the backend and frontend below. Backend La ...

Encountering difficulties connecting to the database within Vue data tables

My php script was working fine with vuetify data, but now every page is showing the error message: Your search for "{{ search }}" found no results. It seems like this issue occurs when the script cannot fetch data from the database. Here is my d ...

"Responding to an Ajax request with a .NET Core server by sending an xlsx

My web application exclusively supports .xlsx files. I have implemented a function in my controller that converts .xls files to .xlsx format successfully. When trying to open a .xls file, I send it via an Ajax request. However, the converted .xlsx file do ...

What steps are involved in a server utilizing Next.js to create a complete document for transmission to the client?

Understanding Next.js has been quite challenging for me. I am struggling to grasp how it operates on the server and how the server is able to implement server side rendering with the files generated by Next.js during the build process. I have a good under ...

What is the most effective way to retrieve 'this' within an object method that is being used as a callback function?

I am currently working on a word game project to enhance my understanding of JavaScript, especially since I am new to it. To facilitate user interaction, I am utilizing the NPM package prompt (https://www.npmjs.com/package/prompt). Coming from an OOP back ...

Is there a way to showcase various category._id within a single page route using Vue.js?

When trying to display multiple categories under a route, clicking on the first category shows the products. However, when clicking on another category, the products do not show up unless I hard refresh the page, which then displays the list of products un ...

Utilizing Universal Windows Platform: Creating Unique Custom Triggers for Background Tasks

I am attempting to create a custom trigger called setTrigger for a background task using javascript. Initially, I believed that utilizing the contentChanged Method would be the solution... taskBuilder.setTrigger(new Windows.ApplicationModel.DataTransfer. ...

Utilize Vue Fullcalendar's eventRender feature to seamlessly incorporate Vue components into your

I am utilizing the fullcalendar.io vue extension. I would like to customize event rendering in order to add actions, but the event callback only contains JavaScript elements. Is there a way to inject a vue component into it? <FullCalendar ref="fu ...

Generating real-time post previews in a web application using .NET MVC 3, similar to the functionality seen on StackOverflow

Looking to create a real-time preview of a form submission, like the one on Stack Overflow. Currently working with .NET MVC 3. Does anyone have suggestions or guidance on how to achieve this? Thank you. - Yohan ...

Changing the active class on Bootstrap nav tabs across pages

My website features a set of navigation tabs on the homepage that provide links for users to access more information. I want the site to automatically navigate to the corresponding tab on another page when a user clicks on the link. If you'd like to c ...

The value of $index remains constant for every page that utilizes dir-paginate

Currently, I am utilizing the dirPaginate directive to handle pagination within my Angular application. While it is functioning correctly overall, I have encountered an issue where each page displays 10 records but the $index values are not incrementing ...