在vue中二级页面返回一级页面

场景:在vue后台管理端项目,需要实现从列表页面跳到详情页面,再从详情页面返回到列表时,列表页面保持跳转之前的状态。

方案一:keep-alive

实践证明,效果是实现了,但是带来了其他问题,会将其他页面的状态都缓存住,而我们只是想要缓存一级列表页面的。所以这方案 pass。

方案二:mixins和vuex

想法是写一个全局的方法,通过 mixins 混入,在需要的页面引进来,这样的话,就可以灵活实现该场景。当然,这里会把列表页面状态存到 vuex 里,在mixins中去调用缓存的状态。
具体实现:

// query.js
export default{
    
    
  watch: {
    
    
    // 深度监听对象里的每个值的变化
    'searchParam': {
    
      // 列表页面需要缓存的对象
      handler() {
    
    
        // 缓存搜索条件及当前路由的name
        this.$store.commit('CACHE_QUERY', this.searchParam)
        // 缓存当前页面路由名称
        this.$store.commit('CACHE_ROUTE_NAME', this.$route.name)
      },
      deep: true
    }
  },
  created() {
    
    
    this.tableParam.total = null
  },
  mounted() {
    
    
    this.parseQuery()
  },
  methods: {
    
    
    parseQuery() {
    
    
      // 存一份初始值,当路由名称不一样时,刷新页面
      if (this.$store.state.app.currentRouteName !== this.$route.name) {
    
    
        // this.searchParam = Object.assign({}, resetData)
        this.$store.commit('CACHE_TAB_INDEX', 'my')
      } else {
    
    
        // 将缓存在 vuex 中的搜索条件,和当前的搜索条件合在一起
        let query = Object.assign({
    
    }, this.$store.state.app.searchQuery)
        this.searchParam = {
    
    ...this.searchParam, ...query}
      }
      // 如果使用了 el-tabs,那在这里先获取存在 vuex 里的 activeName 值,并改变选中项
      this.$parent.$parent.$parent.activeName = this.$parent.$parent.$parent.activeName && this.$store.state.app.currentTabIndex
    }
  }
}

需要注意的是这里的 searchParam 在每个列表页面都有,也就是说每个列表页面需要设置一个对应的 searchParam,它代表每个页面的搜索条件。
再在需要使用的列表页面去使用:

import queryList from '@/commons/mixins/query'

export default {
    
    
    mixins: [queryList]
}

这样的话就达到了我们需要的效果,从二级返回到一级页面,一级页面保持跳转之前的状态。
如果页面有重置按钮,那么在重置的方法里也要加上 this.tableParam.total = null

公众号:Coder 杂谈,欢迎关注
在这里插入图片描述

Supongo que te gusta

Origin blog.csdn.net/qq_42345237/article/details/109568586
Recomendado
Clasificación