Home Web Front-end JS Tutorial vue reduces the number of requests to the server

vue reduces the number of requests to the server

May 02, 2018 pm 03:25 PM
server frequency ask

This time I will bring you vue to reduce the number of requests to the server. What are the precautions for vue to reduce the number of requests to the server? The following is a practical case, let's take a look.

VUE2.0 provides a keep-alive method, which can be used to cache components to avoid loading corresponding components multiple times and 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>
Copy after login
                                                                                                                                                                                            to be cached can be realized by writing the first trigger request into the created hook. 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>
Copy after login
The optimization of the vue project can also be achieved through 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 The requirements of the business, but seeing that every time the page is entered, 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 just so 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: '/home',
          name: home,
          meta:{keepAlive: true}  // 设置为true表示需要缓存,不设置或者false表示不需要缓存          }
          ]
Copy after login

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

Page

Life cycleHooks such as 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

以前的写法是在data中将需要的 $route 数据进行赋值,便于其余方法使用,但是使用了 keep-alive 后数据需要进入页面在activated中再次获取,才能达到更新的目的。定义一个initData方法,然后在activated中启动。

initData: function () {
  let _this = this;
  _this.fromLocation = JSON.parse(this.$route.query.fromLocation);
  _this.toLocation = JSON.parse(this.$route.query.toLocation);
  _this.activeIndex = parseInt(this.$route.params.activeIndex) || 0;
  _this.policyType = parseInt(this.$route.params.policyType) || 0;
  },
Copy after login

      3. 当页动态修改url

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

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

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

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

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

let swiperInstance = new Swiper('#swiper', {
 pagination: '.swiper-pagination',
 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();
 }
});
Copy after login

4. 事件如何处理

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

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

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

5. 地图组件处理

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

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

export default {
 name: 'transferMap',
 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('换乘地图');
  _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();
 },
}
Copy after login

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('iframe');
  iframe.src = '/favicon.ico'; // 必须
  iframe.style.visibility = 'hidden';
  iframe.style.width = '1px';
  iframe.style.height = '1px';
  iframe.onload = function () {
   setTimeout(function () {
    document.body.removeChild(iframe);
   }, 0);
  };
  document.body.appendChild(iframe);
 }, 0);
}
Copy after login

jQuery/Zepto实现

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

实现js同源策略与跨域访问步骤详解

react做出手机数据同步显示在界面功能

The above is the detailed content of vue reduces the number of requests to the server. 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)

How to solve the problem that eMule search cannot connect to the server How to solve the problem that eMule search cannot connect to the server Jan 25, 2024 pm 02:45 PM

Solution: 1. Check the eMule settings to make sure you have entered the correct server address and port number; 2. Check the network connection, make sure the computer is connected to the Internet, and reset the router; 3. Check whether the server is online. If your settings are If there is no problem with the network connection, you need to check whether the server is online; 4. Update the eMule version, visit the eMule official website, and download the latest version of the eMule software; 5. Seek help.

Solution to the inability to connect to the RPC server and the inability to enter the desktop Solution to the inability to connect to the RPC server and the inability to enter the desktop Feb 18, 2024 am 10:34 AM

What should I do if the RPC server is unavailable and cannot be accessed on the desktop? In recent years, computers and the Internet have penetrated into every corner of our lives. As a technology for centralized computing and resource sharing, Remote Procedure Call (RPC) plays a vital role in network communication. However, sometimes we may encounter a situation where the RPC server is unavailable, resulting in the inability to enter the desktop. This article will describe some of the possible causes of this problem and provide solutions. First, we need to understand why the RPC server is unavailable. RPC server is a

Detailed explanation of CentOS installation fuse and CentOS installation server Detailed explanation of CentOS installation fuse and CentOS installation server Feb 13, 2024 pm 08:40 PM

As a LINUX user, we often need to install various software and servers on CentOS. This article will introduce in detail how to install fuse and set up a server on CentOS to help you complete the related operations smoothly. CentOS installation fuseFuse is a user space file system framework that allows unprivileged users to access and operate the file system through a customized file system. Installing fuse on CentOS is very simple, just follow the following steps: 1. Open the terminal and Log in as root user. 2. Use the following command to install the fuse package: ```yuminstallfuse3. Confirm the prompts during the installation process and enter `y` to continue. 4. Installation completed

How to configure Dnsmasq as a DHCP relay server How to configure Dnsmasq as a DHCP relay server Mar 21, 2024 am 08:50 AM

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

Best Practice Guide for Building IP Proxy Servers with PHP Best Practice Guide for Building IP Proxy Servers with PHP Mar 11, 2024 am 08:36 AM

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server

What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline Mar 13, 2024 pm 04:40 PM

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

How to install PHP FFmpeg extension on server? How to install PHP FFmpeg extension on server? Mar 28, 2024 pm 02:39 PM

How to install PHPFFmpeg extension on server? Installing the PHPFFmpeg extension on the server can help us process audio and video files in PHP projects and implement functions such as encoding, decoding, editing, and processing of audio and video files. This article will introduce how to install the PHPFFmpeg extension on the server, as well as specific code examples. First, we need to ensure that PHP and FFmpeg are installed on the server. If FFmpeg is not installed, you can follow the steps below to install FFmpe

Detailed explanation of the advantages and utility of Golang server Detailed explanation of the advantages and utility of Golang server Mar 20, 2024 pm 01:51 PM

Golang is an open source programming language developed by Google. It is efficient, fast and powerful and is widely used in cloud computing, network programming, big data processing and other fields. As a strongly typed, static language, Golang has many advantages when building server-side applications. This article will analyze the advantages and utility of Golang server in detail, and illustrate its power through specific code examples. 1. The high-performance Golang compiler can compile the code into local code

See all articles