前端如何给某些组件设置缓存并处理定位?
最近有个需求就是a=>b,b页面处理了些操作,返回a页面时,
b页面若有操作则a页面需要刷新并定位到上次点击的位置,b若没有操作则无需刷新直接定位上次点击的位置
1.首先在store中存储缓存的组件
javascript
vuex代码:
const cached = {
state: {
cachedPage: []
},
getters: {
getCachedPage (state) {
return state.cachedPage;
}
},
actions: {
addCached ({ commit }, view) {
console.log('view', view)
commit('ADD_CACHED', view)
},
delCached ({ commit }, view) {
commit('DEL_CACHED', view)
}
},
mutations: {
ADD_CACHED: (state, view) => {
if (state.cachedPage.includes(view.name)) return;
state.cachedPage.push(view.name);
},
DEL_CACHED: (state, view) => {
const index = state.cachedPage.indexOf(view.name);
index > -1 && state.cachedPage.splice(index, 1);
},
},
}
export default cached
2.在app.vue组件中使用keep-alive缓存组件
加粗样式
javascript
<keep-alive :include="getCachedPage">
<router-view></router-view>
</keep-alive>
<script >
import { mapGetters } from 'vuex';
export default {
name: 'App',
computed: {
...mapGetters(['getCachedPage']),
},
</script>
3.在需要缓存的组件中,使用组件内的守卫方法,代码如下:
注意:name不要写错了
javascript
export default {
name: 'home',
beforeRouteEnter(to, from, next) {
console.log(from);
store.dispatch('addCached', to);
next((vm) => {
vm.routeName = to.name;
});
},
beforeRouteLeave(to, from, next) {
console.log(to, from);
//记录上次点击的位置
this.scrollTop = document.documentElement.scrollTop;
next();
},
activated() {
//刷新列表
if (this.routeName === 'details') {
//调用刷新列表的接口
} else {
//无需刷新缓存
document.documentElement.scrollTop = this.scrollTop;
}
},
}