Home  >  Article  >  Web Front-end  >  How to use keep-alive in vue2

How to use keep-alive in vue2

php中世界最好的语言
php中世界最好的语言Original
2018-04-14 10:28:081820browse

This time I will bring you how to use keep-alive in vue2. What are the precautions when using keep-alive in vue2. The following is a practical case. Let’s take a look. .

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

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 needs to request the data without caching, and then return to the list page

There are two situations:

1. Click the browser's back button directly.

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 to return to the list page through the link.

So there are three situations here:

1. By default, entering the list page requires requesting data.

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.

Entry file The configuration of 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 that the cache needs to be used, and false to indicate that the cache is not required. And add scrolling behavior scrollBehavior

The configuration of router/index.js is as follows:

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

<template>
 <p class="hello">
 <h1>vue</h1>
 <h2>{{msg}}</h2>
 <router-link to="/detail">跳转到detail页</router-link>
 </p>
</template>
<script>
export default {
 name: 'helloworld',
 data () {
 return {
  msg: 'Welcome to Your Vue.js App'
 };
 },
 methods: {
 ajaxRequest() {
  const obj = {
  'aa': 1
  };
  Promise.all([this.$store.dispatch('testUrl', 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. The detail.vue code is as follows:

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

Two: Use router.meta extension

Assume that there are 3 pages now and 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 is as follows:

Set the meta attribute in route A:

{
 path: '/a',
 name: 'A',
 component: resolve => require(['@/views/a'], resolve),
 meta: {
 keepAlive: true // true 表示需要使用缓存
 }
}
So all the codes under router/index become as follows:

import Vue from 'vue';
import Router from 'vue-router';
// import HelloWorld from '@/views/HelloWorld';
Vue.use(Router);

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

beforeRouteLeave(to, from, next) {
 // 设置下一个路由meta
 to.meta.keepAlive = true; // 让A缓存,不请求数据
 next(); // 跳转到A页面
}
in component B All codes of component B are as follows:

<template>
 <p class="list">
 <h1>{{msg}}</h1>
 <router-link to="/a">返回a页面</router-link>
 </p>
</template>
<script>
export default {
 name: 'list',
 data () {
 return {
  msg: 'Welcome to B Page'
 };
 },
 created() {},
 methods: {
 },
 beforeRouteLeave(to, from, next) {
 // 设置下一个路由meta
 to.meta.keepAlive = true; // 让A缓存,不请求数据
 next(); // 跳转到A页面
 }
};
</script>
Set beforeRouteLeave in the C component:

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

<template>
 <p class="list">
 <h1>{{msg}}</h1>
 <router-link to="/a">返回a页面</router-link>
 </p>
</template>
<script>
export default {
 name: 'list',
 data () {
 return {
  msg: 'Welcome to B Page'
 };
 },
 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>vue</h1>
 <h2>{{msg}}</h2>
 <router-link to="/b">跳转到b页面</router-link>
 <router-link to="/c">跳转到c页面</router-link>
 </p>
</template>
<script>
export default {
 name: 'helloworld',
 data () {
 return {
  msg: 'Welcome to A Page'
 };
 },
 methods: {
 ajaxRequest() {
  const obj = {
  'aa': 1
  };
  Promise.all([this.$store.dispatch('testUrl', 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 component b does not re-request data from component a (including clicking links and browser back buttons), and component c requests data from component a (including clicking links and browser back buttons).

I believe I have read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How nodejs implements gulp packaging function

Analysis of steps for building multi-page applications with webpack

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