Table of Contents
Why do we need to keep the page alive?
How to keep the page alive?
State Storage
What is the problem?
Component caching
What’s the problem? ?
Best Practice
Routing configuration
Keep-alive component storage
Page cache
TypeScript提升配置体验
该方案的问题
总结
Home Web Front-end Vue.js Share an extremely comfortable Vue page keeping solution

Share an extremely comfortable Vue page keeping solution

Apr 10, 2023 pm 04:29 PM
vue.js vue-router

This article brings you relevant knowledge about Vue. It mainly shares with you an extremely comfortable Vue page keeping solution. There are code examples. Friends who are interested can take a look below. I hope everyone has to help.

In order to make page keep-alive more stable, what do you do?

I implemented it with one line of configuration

Share an extremely comfortable Vue page keeping solution

Vue page keep-alive means that after the user leaves the current page, he can Restore the state of the last viewed page. This technology allows users to enjoy a smoother and more natural browsing experience without being disturbed by cumbersome operations.

Why do we need to keep the page alive?

Page keeping alive can improve the user experience. For example, when the user jumps from a table page with pagination ([Page A]) to the data details page ([Page B]), and after viewing the data, when the user returns from [Page B] to [Page A] , if there is no page keep alive, [Page A] will reload and jump to the first page, which will make users very annoyed because they need to re-select the page and data. Therefore, using page keep-alive technology, when the user returns to [Page A], the previously selected page number and data can be restored, making the user experience smoother.

How to keep the page alive?

State Storage

This solution is the most intuitive. The principle is to manually store the state that needs to be kept alive before leaving [Page A]. State can be stored to LocalStore, SessionStore, or IndexedDB. In the onMounted hook of the [Page A] component, check whether the previous state exists, and if so, restore the state from external storage.

What is the problem?

  • Waste of mind (trouble/worry). The problem with this solution is that you need to know clearly when writing the component to store the state when jumping to certain pages.
  • Unable to resolve child component state. You can also save the status of page components in page components, but how to save sub-components. It is impossible to maintain all sub-component states in the page component, because such a structure is not reasonable.

Component caching

Using Vue's built-in components<keepalive></keepalive>Cache the dynamic switching component wrapped in it (also It’s <component></component> component). <keepalive></keepalive>When wrapping dynamic components, inactive components will be cached instead of destroying them. When a component is toggled in <keepalive></keepalive>, the activated and deactivated lifecycle hooks replace mounted and unmountedHook. The most important thing is that <keepalive></keepalive> applies not only to the root node of the wrapped component, but also to its descendant nodes.

<keepalive></keepalive>Paired with vue-router, the page can be kept alive. The implementation code is as follows:

<template>
  <RouterView v-slot="{ Component }">
    <KeepAlive>
      <component :is="Component"/>
    </KeepAlive>
  </RouterView>
</template>
Copy after login

What’s the problem? ?

  • Page keepalive is inaccurate. Although the above method achieves page keep-alive, it cannot meet production requirements. For example: [Page A] is the application homepage, [Page B] is the data list page, and [Page C] is the data details page. The moving line for users to view data details is: [Page A]->[Page B]->[Page C]. In this moving line, [Page B]->[Page C] needs to be cached [ Page B], when changing from [Page C]->[Page B], you need to restore [Page B] from it. However, when [Page B] -> [Page A], there is no need to cache [Page B]. The above method cannot achieve such a configuration.

Best Practice

The most ideal way to keep alive is to achieve on-demand page keepalive through simple configuration without invading the component code.

[No intrusion into component code] This rule eliminates the implementation of the first method. The second method [component caching] is only defeated by [on-demand page keep-alive]. Then transform the second way, by configuring on-demand keep-alive on the routing configuration of router, and then provide a read configuration combined with <KeepAlive/>includeAttributes are enough.

Routing configuration

src/router/index.ts

import useRoutersStore from &#39;@/store/routers&#39;;

const routes: RouteRecordRaw[] = [
  {
    path: &#39;/&#39;,
    name: &#39;index&#39;,
    component: () => import(&#39;@/layout/index.vue&#39;),
    children: [
      {
        path: &#39;/app&#39;,
        name: &#39;App&#39;,
        component: () => import(&#39;@/views/app/index.vue&#39;),
      },
      {
        path: &#39;/data-list&#39;,
        name: &#39;DataList&#39;,
        component: () => import(&#39;@/views/data-list/index.vue&#39;),
        meta: {
          // 离开【/data-list】前往【/data-detail】时缓存【/data-list】
          leaveCaches: [&#39;/data-detail&#39;],
        }
      },
      {
        path: &#39;/data-detail&#39;,
        name: &#39;DataDetail&#39;,
        component: () => import(&#39;@/views/data-detail/index.vue&#39;),
      }
    ]
  }
];

router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  const { cacheRouter } = useRoutersStore();
  cacheRouter(from, to);
  next();
});
Copy after login

Keep-alive component storage

src/stroe /router.ts

import { RouteLocationNormalized } from &#39;vue-router&#39;;

const useRouterStore = defineStore(&#39;router&#39;, {
  state: () => ({
    cacheComps: new Set<string>(),
  }),
  actions: {
    cacheRouter(from: RouteLocationNormalized, to: RouteLocationNormalized) {
      if(
        Array.isArray(from.meta.leaveCaches) && 
        from.meta.leaveCaches.inclued(to.path) && 
        typeof from.name === &#39;string&#39;
      ) {
        this.cacheComps.add(form.name);
      }
      if(
        Array.isArray(to.meta.leaveCaches) && 
        !to.meta.leaveCaches.inclued(from.path) && 
        typeof to.name === &#39;string&#39;
      ) {
        this.cacheComps.delete(to.name);
      }
    },
  },
  getters: {
    keepAliveComps(state: State) {
      return [...state.cacheComps];
    },
  },
});
Copy after login

Page cache

src/layout/index.vue

<template>
  <RouterView v-slot="{ Component }">
    <KeepAlive :include="keepAliveComps">
      <component :is="Component"/>
    </KeepAlive>
  </RouterView>
</template>

<script setup>
import { storeToRefs } from &#39;pinia&#39;;
import useRouterStore from &#39;@/store/router&#39;;

const { keepAliveComps } = storeToRefs(useRouterStore());
</script>
Copy after login

TypeScript提升配置体验

import &#39;vue-router&#39;;

export type LeaveCaches = string[];

declare module &#39;vue-router&#39; {
  interface RouteMeta {
    leaveCaches?: LeaveCaches;
  }
}
Copy after login

该方案的问题

  • 缺少通配符处理/*/**/index
  • 无法缓存/preview/:address这样的动态路由。
  • 组件名和路由名称必须保持一致。

总结

通过<routerview v-slot="{ Component }"></routerview>获取到当前路由对应的组件,在将该组件通过<component :is="Component"></component>渲染,渲染之前利用<keepalive :include="keepAliveComps"></keepalive>来过滤当前组件是否需要保活。 基于上述机制,通过简单的路由配置中的meta.leaveCaches = [...]来配置从当前路由出发到哪些路由时,需要缓存当前路由的内容。【推荐学习:《vue.js视频教程》】

如果大家有其他保活方案,欢迎留言交流哦!

The above is the detailed content of Share an extremely comfortable Vue page keeping solution. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

I encountered the vue-router error 'NavigationDuplicated: Avoided redundant navigation to current location' in my Vue application - how to solve it? I encountered the vue-router error 'NavigationDuplicated: Avoided redundant navigation to current location' in my Vue application - how to solve it? Jun 24, 2023 pm 02:20 PM

The vue-router error "NavigationDuplicated:Avoidedredundantnavigationtocurrentlocation" encountered in the Vue application – how to solve it? Vue.js is becoming more and more popular in front-end application development as a fast and flexible JavaScript framework. VueRouter is a code library of Vue.js used for routing management. However, sometimes

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

Let's talk about how to use the Amap API in vue3 Let's talk about how to use the Amap API in vue3 Mar 09, 2023 pm 07:22 PM

When we used Amap, the official recommended many cases and demos to us, but these cases all used native methods to access and did not provide demos of vue or react. Many people have written about vue2 access on the Internet. However, in this article, we will take a look at how vue3 uses the commonly used Amap API. I hope it will be helpful to everyone!

Detailed example of vue3 realizing the typewriter effect of chatgpt Detailed example of vue3 realizing the typewriter effect of chatgpt Apr 18, 2023 pm 03:40 PM

When I was working on the chatgpt mirror site, I found that some mirror sites did not have typewriter cursor effects, but only text output. Did they not want to do it? I want to do it anyway. So I studied it carefully and realized the effect of typewriter plus cursor. Now I will share my solution and renderings~

Teach you step by step how to use Vue3 to implement an elegant element dragging function Teach you step by step how to use Vue3 to implement an elegant element dragging function Mar 30, 2023 pm 08:57 PM

How to implement element dragging function? The following article will take you step by step to understand how to use Vue3 to implement an elegant element dragging function, and learn relevant knowledge points through examples. I hope it will be helpful to you!

See all articles