Home Web Front-end JS Tutorial How to use keep-alive in vue2

How to use keep-alive in vue2

Jun 19, 2018 pm 02:47 PM
alive keep vue vue2

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:

1

2

3

4

5

<keep-alive>

 <component>

 <!-- 该组件将被缓存! -->

 </component>

</keep-alive>

Copy after login

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:

1

2

3

4

5

<!-- 缓存所有的页面 -->

<keep-alive>

 <router-view v-if="$route.meta.keep_alive"></router-view>

</keep-alive>

<router-view v-if="!$route.meta.keep_alive"></router-view>

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

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;

Copy after login

3. list.vue code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<template>

 <p class="hello">

 <h1>vue</h1>

 <h2>{{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>

Copy after login

4. detail.vue code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<template>

 <p class="list">

 <h1>{{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>

Copy after login

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:

1

2

3

4

5

6

7

8

{

 path: &#39;/a&#39;,

 name: &#39;A&#39;,

 component: resolve => require([&#39;@/views/a&#39;], resolve),

 meta: {

 keepAlive: true // true 表示需要使用缓存

 }

}

Copy after login

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

1

2

3

import Vue from &#39;vue&#39;;

import Router from &#39;vue-router&#39;;

// import HelloWorld from &#39;@/views/HelloWorld&#39;;

Copy after login

Vue.use(Router);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

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;

Copy after login

Set beforeRouteLeave in component B

1

2

3

4

5

beforeRouteLeave(to, from, next) {

 // 设置下一个路由meta

 to.meta.keepAlive = true; // 让A缓存,不请求数据

 next(); // 跳转到A页面

}

Copy after login

All the codes of component B are as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<template>

 <p class="list">

 <h1>{{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>

Copy after login

Set beforeRouteLeave in component C:

All the codes in the

1

2

3

4

5

6

beforeRouteLeave(to, from, next) {

 // 设置下一个路由meta

 to.meta.keepAlive = false; // 让A不缓存,重新请求数据

 console.log(to)

 next(); // 跳转到A页面

}

Copy after login

c component are as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<template>

 <p class="list">

 <h1>{{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>

Copy after login

All the codes in the a component are as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

<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: &#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>

Copy after login

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 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles