網站搜尋

javascript - Vue.js - 在 Vuex 模組中取得當前路由


我有一個帶命名空間的 Vuex 儲存,它會根據當前路由的參數返回儲存中的一個條目。

import Router from '../../router/index'

const options = {
  routeIdentifier: 'stepId'
}

export function fromRoute(state) {
  if (!options.routeIdentifier || !Router.currentRoute.params) {
    return null
  }

  return state.all.find(element => {
    return element.identifier === Router.currentRoute.params[options.routeIdentifier]
  })
}

這在初次載入時如預期運作。然而,每當路由改變時,它不會重新載入。

有沒有辦法在路由變更時重新載入或強制重新計算 getter?

答案#1

在路由模組中匯入商店會比反過來更被支援。你可以使用 beforeEach 導航守衛來在商店中設定當前路由。首先,準備商店:

store.js

state: {
  route: null
},
mutations: {
  SET_ROUTE(state, route) {
    state.route = route;
  }
},
modules: { ... }

在路由模組中,使用 beforeEach 守衛來儲存當前路由,即 to 參數:

router.js

import store from '@/store';  // Import the store in the router module

const router = new VueRouter({
  ...
})

router.beforeEach((to, from, next) => {
  store.commit('SET_ROUTE', to);
  next();
});

要在 Vuex 模組的 getter 中存取此路由,透過第三個 getter 參數 rootState 來存取它:

store/someModule.js

getters: {
  getRoute(state, getters, rootState) {
    return rootState.route;
  }
}