search
HomeWeb Front-endJS TutorialReduce the number of requests to the server through keep-alive provided by vue

This article mainly introduces the keep-alive provided by vue to reduce the number of requests to the server. The article also introduces the points to note when opening keep-alive in vue routing. Friends who need it can refer to it

Let’s look at the keep-alive provided by vue to reduce the number of requests to the server

VUE2.0 provides a keep-alive method, which can be used to cache components and avoid loading corresponding components multiple times. Reduce performance consumption. For example, the data of a page, including pictures, text, etc., have been loaded by the user, and then the user jumps to another interface by clicking on it. Then return to the original interface from another interface. If it is not set, the information of the original interface will be requested from the server again. The keep-alive provided by vue can save the requested data of the page, reduce the number of requests, and improve the user experience.

                                                                                                                                                                                                                                                            Cache components be divided into two types, components to cache the entire site’s pages or components to cache some pages.

1. Cache all pages, suitable for situations where each page has a request. The method is as follows: wrap the router-view that needs to be cached with the keep-alive tag.

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

                                                                                                                                                                                to write the first trigger request into the created hook, can achieve caching. For example, when you go from the list page to the details page, you will still be on the original page when you come back.

2. Cache some components or pages, which can be achieved through judgment using the router.meta attribute. The method is as follows:                                                                                                                                                                                                                                                                                                    The name implies the meaning, include means to include, exclude means to exclude. Here you need to use the name of the component to set it, so the name must be added. Adding components a and b requires caching, while components c and d do not require caching. It is written as follows:

<keep-alive v-if="$route.meta.keepAlive">
      <router-view></router-view>
     </keep-alive>
     <router-view v-if="! $route.meta.keepAlive"></router-view>

The optimization of the vue project can also be achieved through the on-demand loading of components, just like the lazy loading of pictures. If the customer does not see those pictures at all, but we are opening the page When all is loaded, this will greatly increase the request time and reduce the user experience. Lazy loading is used on many websites, such as shopping websites such as Taobao and JD.com. There are many picture links on them. If you pull the scroll down quickly, you may see the pictures loading. Condition.

Supplement:

#Notes when Vue routing turns on keep-alive

This is not Business requirements, but seeing that every time I enter the page, the DOM is re-rendered and then the data is obtained to update the DOM. I feel that as a front-end engineer, it is necessary to optimize the loading logic. It happens that Vue provides the keep-alive function, so I tried it out. . Of course, nothing will be smooth sailing, and bumps and bumps on the road are inevitable, so I record the problems encountered here and hope that people who read this article can help. ps: This is not difficult. HTML part:

 routers:[
        { path: &#39;/home&#39;,
          name: home,
          meta:{keepAlive: true}  // 设置为true表示需要缓存,不设置或者false表示不需要缓存          }
          ]

...1. At what stage is the data obtained?

The page life cycle hook is as shown in the code above, These four are the most commonly used parts. This part needs to be noted. When keep-alive is introduced, when the page is entered for the first time, the trigger sequence of the hook is created->mounted->activated, and deactivated is triggered when exiting. When entering again (forward or backward), only activated is triggered. We know that after keep-alive, the page template is initialized and parsed into an HTML fragment for the first time. When it is entered again, it will not re-parse but read the data in the memory. That is, it will only be used when the data changes. VirtualDOM performs diff updates. Therefore, the data obtained when entering the page should also be placed in activated. After the data is downloaded, the manual operation of the DOM should also be executed in activated to take effect.

So, you should leave a copy of the data acquisition code in activated, or you should leave out the created part and directly transfer the code in created to activated.

2. The data in $route cannot be read

The previous writing method was to assign the required $route data in data to facilitate the use of other methods, but After using keep-alive, the data needs to be entered into the page and obtained again in activated to achieve the purpose of updating. Define an initData method and then start it in activated.

  <keep-alive include="a,b">
      <component></component>
     </keep-alive>  
     <keep-alive exclude="c,d">
      <component></component>
     </keep-alive>

3. Dynamically modify the url on the current page

需求描述:当页面在进行轮播操作的时候希望能记录当前显示的轮播ID(activeIndex)。当进入下一个页面再返回的时候能记住之前的选择,将轮播打到之前的ID位置。所以我想将这部分信息固化在url中,轮播发生变化时,修改URL。这样实现比较符最小修改原则,其余页面不用变动。

之前的写法是将activeIndex放在 $route 的query中,当轮播后,将

activeIndex的值存入 $route.query.activeIndex 中,然后 $router.replace 当前路由,理论上应该能发生变化,但实际没有。

查看文档后说, $route 是只读模式。当然,对象部分是他监管不到的,我修改了并不是正统的做法。

神奇的地方来了:当我将activeIndex记在params中,轮播变动修改params中的参数,然后 $router.replace 当前路由,却能发生对应的变化。代码如下:

let swiperInstance = new Swiper(&#39;#swiper&#39;, {
 pagination: &#39;.swiper-pagination&#39;,
 paginationClickable: false,
 initialSlide: activeIndex,
 onSlideChangeEnd: function (swiper) {
  let _activeIndex = swiper.activeIndex;
  _this.$route.params.activeIndex = _activeIndex;
  // $router我放到了window上方便调用
  window.$router.replace({
   name: _this.$route.name,
   params: _this.$route.params,
   query: _this.$route.query
  });
  // 根据activeIndex,在这里初始化下面显示的数据
  _this.transferDetail = _this.allData.plans[_activeIndex].segments;
  _this.clearBusDetailFoldState();
 }
});

4. 事件如何处理

估计你也能猜到,发生的问题是事件绑定了很多次,比如上传点击input监听change事件,突然显示了多张相同图片的问题。

也就是说,DOM在编译后就缓存在内容中了,如果再次进入还再进行事件绑定初始化则就会发生这个问题。

解决办法:在mounted中绑定事件,因为这个只执行一次,并且DOM已准备好。如果插件绑定后还要再执行一下事件的handler函数的话,那就提取出来,放在activated中执行。比如:根据输入内容自动增长textarea的高度,这部分需要监听textarea的input和change事件,并且页面进入后还要再次执行一次handler函数,更新textarea高度(避免上次输入的影响)。

5. 地图组件处理

想必这是使用 keep-alive 最直接的性能表现。之前是进入地图页面后进行地图渲染+线路标记;现在是清除以前的线路标记绘制新的线路,性能优化可想而知!

我这里使用的是高德地图,在mounted中初始化map,代码示例如下:

export default {
 name: &#39;transferMap&#39;,
 data: function () {
  return {
   map: null,
  }
 },
 methods: {
  initData: function () {},
  searchTransfer: function (type) {},
  // 地图渲染 这个在transfer-map.html中使用
  renderTransferMap: function (transferMap) {}
 },
 mounted: function () {
  this.map = new AMap.Map("container", {
   showBuildingBlock: true,
   animateEnable: true,
   resizeEnable: true,
   zoom: 12 //地图显示的缩放级别
  });
 },
 activated: function () {
  let _this = this;
  _this.initData();
  // 设置title
  setDocumentTitle(&#39;换乘地图&#39;);
  _this.searchTransfer(_this.policyType).then(function (result) {
   // 数据加载完成
   // 换乘地图页面
   let transferMap = result.plans[_this.activeIndex];
   transferMap.origin = result.origin;
   transferMap.destination = result.destination;
   // 填数据
   _this.transferMap = transferMap;
   // 地图渲染
   _this.renderTransferMap(transferMap);
  });
 },
 deactivated: function () {
  // 清理地图之前的标记
  this.map.clearMap();
 },
}

6. document.title修改

这个不是 keep-alive 的问题,不过我也在这里分享下。

问题是,使用下面这段方法,可以修改Title,但是页面来回切换多次后就不生效了,我也不知道为啥,放到setTimeout中就直接不执行。

document.title = '页面名称';下面是使用2种环境的修复方法:

纯js实现

function setDocumentTitle(title) {
 "use strict";
 //以下代码可以解决以上问题,不依赖jq
 setTimeout(function () {
  //利用iframe的onload事件刷新页面
  document.title = title;
  var iframe = document.createElement(&#39;iframe&#39;);
  iframe.src = &#39;/favicon.ico&#39;; // 必须
  iframe.style.visibility = &#39;hidden&#39;;
  iframe.style.width = &#39;1px&#39;;
  iframe.style.height = &#39;1px&#39;;
  iframe.onload = function () {
   setTimeout(function () {
    document.body.removeChild(iframe);
   }, 0);
  };
  document.body.appendChild(iframe);
 }, 0);
}

jQuery/Zepto实现

function setDocumentTitle(title) {
 //需要jQuery
 var $body = $(&#39;body&#39;);
 document.title = title;
 // hack在微信等webview中无法修改document.title的情况
 var $iframe = $(&#39;<iframe src="/favicon.ico"></iframe>&#39;);
 $iframe.on(&#39;load&#39;, function () {
  setTimeout(function () {
   $iframe.off(&#39;load&#39;).remove();
  }, 0);
 }).appendTo($body);
}

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

vue 指定组件缓存实例详解

使用JSON格式提交数据到服务端的实例代码

JavaScript动态加载重复绑定问题

The above is the detailed content of Reduce the number of requests to the server through keep-alive provided by vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools