测试对你提出一个需求,去了其他模块页面,回来不要初始化列表数据?
这里用的后端分页,那只需缓存分页参数就好啦。直接开始写代码:(假设基于vue的elementui。分页是封装起来的一个公共组件)
那我们在分页组件里面统一处理,在切换当前页或者每页条数操作handleSizeChange、handleCurrentChange时,将参数根据路由名称(唯一)name缓存在store里面,当然文中的'page/changePageSize'可以勇vuex的辅助函数mapActions来重命名处理
pagination.vue
<template>
<div :class="{ hidden: hidden }" class="pagination-container">
<el-pagination
:background="background"
:current-page.sync="currentPage"
:page-size.sync="pageSize"
:layout="layout"
:page-sizes="pageSizes"
:total="total"
v-bind="$attrs"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</div>
</template>
import { scrollTo } from '@/utils/scroll-to'
export default {
name: 'Pagination',
props: {
page: {
type: Number,
default: 1
},
limit: {
type: Number,
default: 20
},
pageSizes: {
type: Array,
default() {
return [10, 20, 30, 50]
}
},
...
hidden: {
type: Boolean,
default: false
}
},
computed: {
currentPage: {
get() {
return this.page
},
set(val) {
this.$emit('update:page', val)
}
},
pageSize: {
get() {
return this.limit
},
set(val) {
this.$emit('update:limit', val)
}
}
},
methods: {
handleSizeChange(val) {
// 改变的size存store key为路由名 value为size
this.$store.dispatch('page/changePageSize', {
[this.$route.name]: val
})
this.$emit('pagination', { page: this.currentPage, limit: val })
if (this.autoScroll) {
scrollTo(0, 800)
}
},
handleCurrentChange(val) {
// 改变的Current存store key为路由名 value为Current
this.$store.dispatch('page/changePageCurrent', {
[this.$route.name]: val
})
this.$emit('pagination', { page: val, limit: this.pageSize })
if (this.autoScroll) {
scrollTo(0, 800)
}
}
}
}
store里面,给当前页与每页条数声明并且操作
// store/page.js
const state = {
size: {}, // 每页条数
current: {}, // 当前页
}
const mutations = {
SET_SIZE: (state, size) => {
state.size = { ...state.size, ...size }
},
SET_CURRENT: (state, current) => {
state.current = { ...state.current, ...current }
}
}
const actions = {
changePageSize({ commit }, size) {
commit('SET_SIZE', size)
},
changePageCurrent({ commit }, current) {
commit('SET_CURRENT', current)
}sheng
}
export default {
namespaced: true,
state,
mutations,
actions
}
// store/getters.js
const getters = {
sidebar: state => state.app.sidebar,
pageSizeByRouteName: state => state.page.size,
pageCurrentByRouteName: state => state.page.current
}
export default getters
具体在使用的业务组件中,每次请求数据时先看一下是否缓存数据。
async getData() {
this.listLoading = true
const current = this.$store.getters.pageCurrentByRouteName[this.$route.name]
if (current) this.formInline = { ...this.formInline, current }
const size = this.$store.getters.pageSizeByRouteName[this.$route.name]
if (size) this.formInline = { ...this.formInline, size }
...
}