You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js同路由组件返回状态保存:下拉重置/返回保留年份

解决方案:用Vuex管理年份状态实现场景需求

核心思路

把年份状态从组件本地迁移到Vuex中共享,仅在切换下拉菜单时重置为当前年,从详情页返回时保留已选年份,同时调整组件初始化逻辑避免不必要的年份重置。


步骤1:配置Vuex年份状态模块

创建专门的模块管理年份状态,包含设置年份和重置为当前年的操作:

// store/modules/claimYear.js
const state = {
  // 初始值设为当前年份
  selectedYear: new Date().getFullYear()
}

const mutations = {
  // 设置选中年份
  SET_SELECTED_YEAR(state, year) {
    state.selectedYear = year
  },
  // 重置为当前年份
  RESET_TO_CURRENT_YEAR(state) {
    state.selectedYear = new Date().getFullYear()
  }
}

const actions = {
  setSelectedYear({ commit }, year) {
    commit('SET_SELECTED_YEAR', year)
  },
  resetToCurrentYear({ commit }) {
    commit('RESET_TO_CURRENT_YEAR')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

在主Store中引入该模块:

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import claimYear from './modules/claimYear'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    claimYear
  }
})

步骤2:修改组件代码

2.1 映射Vuex状态与方法

在组件中引入Vuex辅助函数,映射年份状态和操作方法:

import { mapState, mapActions } from 'vuex'

export default {
  computed: {
    // 映射Vuex中的selectedYear到组件
    ...mapState('claimYear', ['selectedYear'])
  },
  methods: {
    // 映射Vuex中的年份操作方法
    ...mapActions('claimYear', ['setSelectedYear', 'resetToCurrentYear']),
    // 其他组件方法...
  }
}

2.2 调整下拉切换逻辑

移除changeDdVal中直接赋值年份的代码,改为调用Vuex的重置方法,仅在切换下拉时重置年份:

changeDdVal(v) {
  this.$store.dispatch('getUserRoles').then(userRoles => {
    if (userRoles.admin) {
      // 切换下拉选项时,重置年份为当前年
      this.resetToCurrentYear()
      switch (v) {
        case 1:
          this.dropValue = "salesClaimCount";
          this.headerDropdownClaim = "sales";
          this.tableHeadData = this.salesTableHeadData;
          this.api.filterData = "getSalesClaimFilterDataForApprover";
          this.$router.push({name: this.routeName, params: {approverClaimType: this.claimTableData.claimStatus, dropType: this.headerDropdownClaim, userRole: this.role}})
            .catch(() => {});
          this.yearChange();
          break;
        case 2:
          this.dropValue = "staffingClaimCount";
          this.headerDropdownClaim = "staffing";
          this.tableHeadData = this.placementTableHeadData;
          this.api.filterData = "getStaffingClaimFilterDataForApprover";
          this.$router.push({name: this.routeName, params: {approverClaimType: this.claimTableData.claimStatus, dropType: this.headerDropdownClaim, userRole: this.role}})
            .catch(() => {});
          this.yearChange();
          break;
      }
    }
  })
}

2.3 修改年份切换逻辑

用户选择年份时,更新Vuex中的状态;yearChange直接使用Vuex中的年份:

// 用户选择年份的触发方法
onYearSelect(year) {
  this.setSelectedYear(year)
  this.yearChange()
}

// 调整yearChange函数
yearChange() {
  this.axiosCancelToken.cancel("cancel requested")
  this.changeYear = false;
  this.firstLoad = true;
  this.sortBy =  "claimId";
  this.sortType = "descending";
  this.handlePagination(this.paginationOptions);
  this.mavePaginationList(false);
  this.fetchData();
  var dataApi = new FormData();
  // 直接使用Vuex中的selectedYear
  dataApi.append("year", this.selectedYear);
  api
    .post(this.api.filterData, {data: dataApi})
    .then((res) => {
      // 处理响应逻辑
    })
},

2.4 优化组件初始化逻辑

避免每次组件创建都调用changeDdVal重置年份,仅在首次加载或非返回场景执行:

created() {
  // 判断是否从详情页返回(假设详情页路由name为'ClaimDetail')
  const isFromDetail = this.$route.from?.name === 'ClaimDetail'
  if (!isFromDetail) {
    // 首次进入或非返回场景,调用下拉初始化
    this.changeDdVal(/* 默认下拉值,比如1 */);
  } else {
    // 从详情页返回,直接用Vuex年份刷新数据
    this.yearChange();
  }
}

内容的提问来源于stack exchange,提问作者user17320926

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:50:16