search
HomeWeb Front-endJS TutorialHow to use keep-alive in vue2
How to use keep-alive in vue2Jun 19, 2018 pm 02:47 PM
alivekeepvuevue2

vue2.0 provides a keep-alive component to cache components to avoid loading corresponding components multiple times and reduce performance consumption. This article introduces to you a summary and precautions for the use of keep-alive in vue2. Friends who need it can refer to it

keep-alive is a built-in component of Vue, which can retain the state in the memory during the component switching process. Prevent repeated rendering of the DOM. Combined with vue-router, the entire content of a view can be cached.

The basic usage is as follows:

<keep-alive>
 <component>
 <!-- 该组件将被缓存! -->
 </component>
</keep-alive>

Generally there is such a demand. When we enter the list page for the first time, we need to request data. When I enter the details page from the list page, the details page is not cached. You need to request data and then return to the list page

There are two situations:

1. Directly click the browser's back button.

2. Click the /list link in the navigation bar to return.

So in the first case, when we directly use the back button to return to the list page (/list), there is no need to request data.

In the second case, we need to request data by returning to the list page through the link.

So there are three situations here:

#1. By default, data needs to be requested when entering the list page.

2. After entering the details page, use the browser's default back button to return, which does not require an ajax request.

3. After entering the details page and returning to the list page by clicking the link, you also need to send an ajax request.

The configuration is as follows:

1. The configuration of the entry file app.vue is as follows:

<!-- 缓存所有的页面 -->
<keep-alive>
 <router-view v-if="$route.meta.keep_alive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keep_alive"></router-view>

2. Set the meta attribute in the router and set keepAlive: true to indicate the need to use cache , if false, it means no need to use cache. And add scroll behavior scrollBehavior

router/index.js configuration is as follows:

import Vue from &#39;vue&#39;;
import Router from &#39;vue-router&#39;;
// import HelloWorld from &#39;@/views/HelloWorld&#39;;
Vue.use(Router);
const router = new Router({
 mode: &#39;history&#39;, // 访问路径不带井号 需要使用 history模式,才能使用 scrollBehavior
 base: &#39;/page/app&#39;, // 配置单页应用的基路径
 routes: [
 {
  path: &#39;/&#39;,
  name: &#39;list&#39;,
  component: resolve => require([&#39;@/views/list&#39;], resolve), // 使用懒加载
  meta: {
  keepAlive: true // true 表示需要使用缓存
  }
 },
 {
  path: &#39;/list&#39;,
  name: &#39;list&#39;,
  component: resolve => require([&#39;@/views/list&#39;], resolve), // 使用懒加载
  meta: {
  keepAlive: true // true 表示需要使用缓存 false表示不需要被缓存
  }
 },
 {
  path: &#39;/detail&#39;,
  name: &#39;detail&#39;,
  component: resolve => require([&#39;@/views/detail&#39;], resolve) // 使用懒加载
 }
 ],
 scrollBehavior (to, from, savedPosition) {
 // 保存到 meta 中,备用
 to.meta.savedPosition = savedPosition;
 if (savedPosition) {
  return { x: 0, y: 0 };
 }
 return {};
 }
});
export default router;

3. list.vue code is as follows:

<template>
 <p class="hello">
 <h1 id="vue">vue</h1>
 <h2 id="msg">{{msg}}</h2>
 <router-link to="/detail">跳转到detail页</router-link>
 </p>
</template>

<script>
export default {
 name: &#39;helloworld&#39;,
 data () {
 return {
  msg: &#39;Welcome to Your Vue.js App&#39;
 };
 },
 methods: {
 ajaxRequest() {
  const obj = {
  &#39;aa&#39;: 1
  };
  Promise.all([this.$store.dispatch(&#39;testUrl&#39;, obj)]).then((res) => {
  console.log(res);
  });
 }
 },
 beforeRouteEnter(to, from, next) {
 next(vm => {
  /*
  如果 to.meta.savedPosition === undefined 说明是刷新页面或可以叫第一次进入页面 需要刷新数据
  如果savedPosition === null, 那么说明是点击了导航链接;
  此时需要刷新数据,获取新的列表内容。
  否则的话 什么都不做,直接使用 keep-alive中的缓存
  */
  if (to.meta.savedPosition === undefined) {
  vm.ajaxRequest();
  }
  if (to.meta.savedPosition === null) {
  vm.ajaxRequest();
  }
 })
 }
};
</script>

4. detail.vue code is as follows:

<template>
 <p class="list">
 <h1 id="msg">{{msg}}</h1>
 <router-link to="/list">返回列表页</router-link>
 </p>
</template>
<script>
export default {
 name: &#39;list&#39;,
 data () {
 return {
  msg: &#39;Welcome to Your Vue.js App&#39;
 };
 },
 created() {
 this.ajaxRequest();
 },
 methods: {
 ajaxRequest() {
  const obj = {
  &#39;aa&#39;: 1
  };
  Promise.all([this.$store.dispatch(&#39;withdary&#39;, obj)]).then((res) => {
  console.log(res);
  });
 }
 }
};
</script>

Two: Use router.meta extension

Assume there are 3 pages now, the requirements are as follows:

1. There is page A by default, and a request is required for page A to come in.

2. Page B jumps to page A, and page A does not need to be requested again.

3. Page C jumps to page A, and page A needs to be requested again.

The implementation method is as follows:

Set the meta attribute in route A:

{
 path: &#39;/a&#39;,
 name: &#39;A&#39;,
 component: resolve => require([&#39;@/views/a&#39;], resolve),
 meta: {
 keepAlive: true // true 表示需要使用缓存
 }
}

So all the codes under router/index become as follows:

import Vue from &#39;vue&#39;;
import Router from &#39;vue-router&#39;;
// import HelloWorld from &#39;@/views/HelloWorld&#39;;

Vue.use(Router);

const router = new Router({
 mode: &#39;history&#39;, // 访问路径不带井号 需要使用 history模式,才能使用 scrollBehavior
 base: &#39;/page/app&#39;, // 配置单页应用的基路径
 routes: [
 {
  path: &#39;/&#39;,
  name: &#39;list&#39;,
  component: resolve => require([&#39;@/views/list&#39;], resolve), // 使用懒加载
  meta: {
  keepAlive: true // true 表示需要使用缓存
  }
 },
 {
  path: &#39;/list&#39;,
  name: &#39;list&#39;,
  component: resolve => require([&#39;@/views/list&#39;], resolve), // 使用懒加载
  meta: {
  keepAlive: true // true 表示需要使用缓存 false表示不需要被缓存
  }
 },
 {
  path: &#39;/detail&#39;,
  name: &#39;detail&#39;,
  component: resolve => require([&#39;@/views/detail&#39;], resolve) // 使用懒加载
 },
 {
  path: &#39;/a&#39;,
  name: &#39;A&#39;,
  component: resolve => require([&#39;@/views/a&#39;], resolve),
  meta: {
  keepAlive: true // true 表示需要使用缓存
  }
 },
 {
  path: &#39;/b&#39;,
  name: &#39;B&#39;,
  component: resolve => require([&#39;@/views/b&#39;], resolve)
 },
 {
  path: &#39;/c&#39;,
  name: &#39;C&#39;,
  component: resolve => require([&#39;@/views/c&#39;], resolve)
 }
 ],
 scrollBehavior (to, from, savedPosition) {
 // 保存到 meta 中,备用
 to.meta.savedPosition = savedPosition;
 if (savedPosition) {
  return { x: 0, y: 0 };
 }
 return {};
 }
});
export default router;

Set beforeRouteLeave in component B

beforeRouteLeave(to, from, next) {
 // 设置下一个路由meta
 to.meta.keepAlive = true; // 让A缓存,不请求数据
 next(); // 跳转到A页面
}

All the codes of component B are as follows:

<template>
 <p class="list">
 <h1 id="msg">{{msg}}</h1>
 <router-link to="/a">返回a页面</router-link>
 </p>
</template>

<script>
export default {
 name: &#39;list&#39;,
 data () {
 return {
  msg: &#39;Welcome to B Page&#39;
 };
 },
 created() {},
 methods: {
 },
 beforeRouteLeave(to, from, next) {
 // 设置下一个路由meta
 to.meta.keepAlive = true; // 让A缓存,不请求数据
 next(); // 跳转到A页面
 }
};
</script>

Set beforeRouteLeave in component C:

All the codes in the
beforeRouteLeave(to, from, next) {
 // 设置下一个路由meta
 to.meta.keepAlive = false; // 让A不缓存,重新请求数据
 console.log(to)
 next(); // 跳转到A页面
}

c component are as follows:

<template>
 <p class="list">
 <h1 id="msg">{{msg}}</h1>
 <router-link to="/a">返回a页面</router-link>
 </p>
</template>

<script>
export default {
 name: &#39;list&#39;,
 data () {
 return {
  msg: &#39;Welcome to B Page&#39;
 };
 },
 created() {},
 methods: {
 },
 beforeRouteLeave(to, from, next) {
 // 设置下一个路由meta
 to.meta.keepAlive = false; // 让A不缓存,重新请求数据
 console.log(to)
 next(); // 跳转到A页面
 }
};
</script>

All the codes in the a component are as follows:

<template>
 <p class="hello">
 <h1 id="vue">vue</h1>
 <h2 id="msg">{{msg}}</h2>
 <router-link to="/b">跳转到b页面</router-link>
 <router-link to="/c">跳转到c页面</router-link>
 </p>
</template>

<script>
export default {
 name: &#39;helloworld&#39;,
 data () {
 return {
  msg: &#39;Welcome to A Page&#39;
 };
 },
 methods: {
 ajaxRequest() {
  const obj = {
  &#39;aa&#39;: 1
  };
  Promise.all([this.$store.dispatch(&#39;testUrl&#39;, obj)]).then((res) => {});
 }
 },
 beforeRouteEnter(to, from, next) {
 next(vm => {
  /*
  如果 to.meta.savedPosition === undefined 说明是刷新页面或可以叫第一次进入页面 需要刷新数据
  如果to.meta.keepAlive === false, 那么说明是需要请求的;
  此时需要刷新数据,获取新的列表内容。
  否则的话 什么都不做,直接使用 keep-alive中的缓存
  */
  if (to.meta.savedPosition === undefined) {
  vm.ajaxRequest();
  }
  if (!to.meta.keepAlive) {
  vm.ajaxRequest();
  }
 })
 }
};
</script>

Note that the b component does not re-request data from the a component (including clicked links and browsers) Back button), the c component requests data from the a component (including clicked links and browser back buttons).

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Using Koa to build projects through Node.js

Is using JavaScript a better solution than asynchronous implementation?

About the use of Vue high-order components

Detailed introduction to Vue data binding

About Website generation chapter directory code example

How to use treeview to dynamically load data in the Bootstrap framework

The above is the detailed content of How to use keep-alive in vue2. 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
vue2与vue3中的生命周期执行顺序有什么区别vue2与vue3中的生命周期执行顺序有什么区别May 16, 2023 pm 09:40 PM

vue2与vue3中生命周期执行顺序区别生命周期比较vue2中执行顺序beforeCreate=>created=>beforeMount=>mounted=>beforeUpdate=>updated=>beforeDestroy=>destroyedvue3中执行顺序setup=>onBeforeMount=>onMounted=>onBeforeUpdate=>onUpdated=>onBeforeUnmount=&g

快速搞懂Vue2 diff算法(图文详解)快速搞懂Vue2 diff算法(图文详解)Mar 17, 2023 pm 08:23 PM

diff算法是一种通过同层的树节点进行比较的高效算法,避免了对树进行逐层搜索遍历。那么大家对diff算法吗有多少了解?下面本篇文章就来带大家深入解析下vue2的diff算法,希望对大家有所帮助!

keep如何添加跑步记录keep如何添加跑步记录Mar 07, 2024 pm 06:00 PM

keep如何添加跑步记录?在keep应用中是可以添加跑步记录,但是多数的用户不知道如何添加跑步记录,接下来就是小编为用户带来的keep添加跑步记录方法图文教程,感兴趣的用户快来一起看看吧!keep如何添加跑步记录1、首先打开keep,首页面点击右下角【我】进入专区,选择右上角【设置】按钮;2、之后跳转到设置功能页,滑动选择【keep实验室】服务;3、然后在keep实验室页面中,点击【佳明跑步记录录入】;4、接着在佳明跑步记录导入页面,最底部【同步记录】按钮点击,跳转窗口选择【确定】;5、最后在下

keep手环怎么连接微信keep手环怎么连接微信Mar 07, 2024 pm 05:20 PM

keep手环怎么连接微信?在keep手环中是可以同步数据到微信中,多数的用户不知道如何连接微信数据,接下来就是小编为用户带来的keep手环连接微信方法图文教程,感兴趣的用户快来一起看看吧!keep手环怎么连接微信1、首先打开keep应用,进入到【我的运动】专区选择右上角按钮;2、之后在下图所示的页面,点击已经绑定的keep手环设备;3、然后跳转到下图的界面,选择【微信运动】;4、最后在如下图所示的页面点击【去绑定】选型即可连接微信。

keep如何连接华为手环keep如何连接华为手环Mar 07, 2024 pm 09:46 PM

keep如何连接华为手环?在keep软件中是可以连接华为手环,多数的用户不知道如何连接华为手环,接下来就是小编为用户带来的keep连接华为手环方法图文教程,感兴趣的用户快来一起看看吧!keep如何连接华为手环1、首先打开keep应用,主页面点击右下角【我】进入专区,选择【智能硬件】;2、之后挑战到我的智能设备功能页,点击中间的【添加设备】;3、然后在选择你要添加的设备页面,选择【智能手环/手表】功能;4、最后在下图所示的界面,点击华为手表型号即可连接。

keep如何刷跑步里程 keep刷跑步历程的方法介绍keep如何刷跑步里程 keep刷跑步历程的方法介绍Mar 12, 2024 pm 01:28 PM

  keep如何刷跑步里程?keep是一款非常热门的健身健美软件,帮助用户们轻松打造出健康好身材。软件支持多样化运动的数据记录,不论你选择哪种运动方式,都能为你记录下数据,让你感受每一次健身带来的变化,给与你坚持的动力。当我们在跑步的时候搜,系统也能实时记录下我们的跑步历程,生成运动记录。不过有很多新手小伙伴不清楚如何刷跑步历程。对此,小编带来了详细的方法介绍,一起看看吧。  keep刷跑步历程的方法介绍  1、开启跑步功能打开KEEP,点击【跑步】。  2、打开设置页面点击右上角设置图标,打开

keep怎么取消自动续费 苹果手机怎样关闭keep续费功能keep怎么取消自动续费 苹果手机怎样关闭keep续费功能Mar 23, 2024 pm 09:10 PM

  keep这一直以来都是特别专业好用的运动健身平台,都能让大家自由的选择运动方式,大家随时随地都能够进行锻炼的,没有什么局限性的,整个的运动课程视频非常的多,都能够让大家跟着课程视频一起锻炼的话,就算大家不去健身房,一样都能获得很好的健身效果哦,当然有一些课程是需要大家有会员才能看的,就是需要大家开通会员的,且关于会员的自动续费选项,大家都还是不太清楚的,所以小编今天给你们分享的就是keep关闭会员自动续费方法,大家可以看一看的。keep关闭会员自动续费方法:  安卓手机:  1、打开keep

《keep》怎么免费拿奖牌《keep》怎么免费拿奖牌Mar 11, 2024 pm 01:50 PM

如何免费获得Keep运动App的奖牌?不用担心,我们将在本文中分享一些独特的技巧和策略,帮助您轻松获得Keep运动App的奖牌。无需花费一分钱,只需遵循我们的建议,您就能在Keep运动App上积累一枚又一枚令人炫目的奖牌!让我们一起来探索这个令人兴奋的免费奖牌获取之路吧!keep怎么免费拿奖牌1、首先打开keep应用,在推荐页面选择【活动挑战】按钮;2、然后在活动中心中,选择自己喜爱感兴趣的活动点击;3、之后活动详情页面滑动到最底部,点击【马上报名】;4、最后在keep旅程中参加活动即可免费获得

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment