Share an extremely comfortable Vue page keeping solution
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
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 unmounted
Hook. 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>
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/>
include
Attributes are enough.
Routing configuration
src/router/index.ts
import useRoutersStore from '@/store/routers'; const routes: RouteRecordRaw[] = [ { path: '/', name: 'index', component: () => import('@/layout/index.vue'), children: [ { path: '/app', name: 'App', component: () => import('@/views/app/index.vue'), }, { path: '/data-list', name: 'DataList', component: () => import('@/views/data-list/index.vue'), meta: { // 离开【/data-list】前往【/data-detail】时缓存【/data-list】 leaveCaches: ['/data-detail'], } }, { path: '/data-detail', name: 'DataDetail', component: () => import('@/views/data-detail/index.vue'), } ] } ]; router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => { const { cacheRouter } = useRoutersStore(); cacheRouter(from, to); next(); });
Keep-alive component storage
src/stroe /router.ts
import { RouteLocationNormalized } from 'vue-router'; const useRouterStore = defineStore('router', { 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 === 'string' ) { this.cacheComps.add(form.name); } if( Array.isArray(to.meta.leaveCaches) && !to.meta.leaveCaches.inclued(from.path) && typeof to.name === 'string' ) { this.cacheComps.delete(to.name); } }, }, getters: { keepAliveComps(state: State) { return [...state.cacheComps]; }, }, });
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 'pinia'; import useRouterStore from '@/store/router'; const { keepAliveComps } = storeToRefs(useRouterStore()); </script>
TypeScript提升配置体验
import 'vue-router'; export type LeaveCaches = string[]; declare module 'vue-router' { interface RouteMeta { leaveCaches?: LeaveCaches; } }
该方案的问题
-
缺少通配符处理
/*
、/**/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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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.

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.

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.

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!

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~

In short: JavaScript + React + Redux still dominate. Best paired with Next.js and Vercel. AI is advancing rapidly and Web3 is experiencing strong growth. There's been a lot of change over the past year, and it feels like everything is ready to be disrupted, but despite being the most disruptive year I've ever seen, the biggest surprise about this year's framework ecosystem is that very little has changed. While there are a lot of new players entering the market (hurray SolidJS), last year's big winners are still dominating this year and seem to show no signs of giving up in the job market (data to back it up). So what has changed? AI Accelerates Developers When I Made My First Time in 2020
