路由独享的守卫---beforeRouteLeave

534 阅读1分钟

场景:刷新默认在'产品'导航栏,点击详情后返回仍然是‘方案’导航栏

myCenter.js(vuex)使用vux保存导航栏的选中状态

  export const state = () => {
    return {
      myCenterSelect: 'Product',
    };
  };

 export const getters = {
    getMyCenterSelect(state) {
      return state.myCenterSelect;
    },
  };

 export const mutations = {
   SET_MY_CENTER_SELECT(state, payload) {
     state.myCenterSelect = payload;
   },
 };
 export const actions = {
  setMyCenterSelect({ commit }, payload) {
    commit('SET_MY_CENTER_SELECT', payload);
  },
};

获取状态

computed: {
  ...mapGetters({
    myCenterSelect: 'myCenter/getMyCenterSelect',
  }),
},

修改状态函数

  // 点击菜单栏
  typeChanged(item, bool = true) {
    this.typeSelected = item;
    this.worksType = item;
    this.$store.commit('myCenter/SET_MY_CENTER_SELECT', item);
  },
  

使用组件导航守卫进行判断(如果跳转不是详情页,则将状态重置,即默认选中‘产品’)

beforeRouteLeave(to, from, next) {
  if (to.path !== '/info/product') {
    this.$store.dispatch('myCenter/setMyCenterSelect', 'Product');
  }
  next();
},