vue2中的keep-alive使用总结及注意事项

2020-06-16 06:30:32易采站长站整理

return { x: 0, y: 0 };
}
return {};
}
});
export default router;

3. list.vue 代码如下:


<template>
<div class="hello">
<h1>vue</h1>
<h2>{{msg}}</h2>
<router-link to="/detail">跳转到detail页</router-link>
</div>
</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. detail.vue 代码如下:


<template>
<div class="list">
<h1>{{msg}}</h1>
<router-link to="/list">返回列表页</router-link>
</div>
</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>

二:使用router.meta 扩展

假设现在有3个页面,需求如下:

1. 默认有A页面,A页面进来需要一个请求。

2. B页面跳转到A页面,A页面不需要重新请求。

3. C页面跳转到A页面,A页面需要重新请求。

实现方式如下:

在 A 路由里面设置 meta 属性:


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

所以router/index下的所有代码变为如下:


import Vue from 'vue';
import Router from 'vue-router';
// import HelloWorld from '@/views/HelloWorld';

Vue.use(Router);