【问题标题】:Load Vuex state on startup based on route params根据路由参数在启动时加载 Vuex 状态
【发布时间】:2021-04-22 16:30:11
【问题描述】:

我有一个 Vue 应用程序,其中包含许多具有 tenantId 参数的路由。第一次加载应用程序时,我必须从路由中获取tenantId 值,从 API 加载数据并用它初始化 Veux 存储。

我不应该显示任何路由器视图组件,因为它假定初始状态已经加载。

所以,我尝试在 App.vue createdmounted 钩子中实现它,但没有运气,因为 $route 在那个阶段是空的。 beforeRouteEnter 不调用 App.vue。在router 模块中的beforeEach 内部,我没有对商店的引用。

这种初始化的正确位置是什么?

【问题讨论】:

标签: vue.js vuex vue-router


【解决方案1】:

您可以在 app.jsmain.js 文件(初始化 Vue 的入口点)中引用 Vuex 存储。这样的东西应该可以工作(未经测试)。

import Vue from 'vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'

Vue.use(Vuex)
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    // routes here
  ]
})

const store = new Vuex.Store({
  state: {
    tenantId: null,
  },
  mutations: {
    setTenant: (state, tenantId) => (state.tenantId = tenantId)
  }
})

const split = window.location.pathname.split('/')
// find the index of the tenantId
// you can also use RegEx for this
const tenantId = //

store.commit('setTenant', tenantId)

const app = new Vue({
  el: '#app',
  router,
  store
})

【讨论】:

  • 感谢您的回答。但在这种情况下,我将复制路由器的逻辑。如果路由发生变化,我还需要在第二个文件中维护它。是否可以“要求”路由器解析 URL,并解析参数?
  • 您不必这样做。您可以只导入现有的router
【解决方案2】:

对我有用的解决方案是在 App.vue 中添加一个beforeEach,其中我还引用了 Vuex 商店。

    // App.vue
    created() {
      this.$router.beforeEach(async (to, _, next) => {
        if (to.params && to.params.tenantId) {
          const id = parseInt(to.params.tenantId, 10);
          if (id != this.$store.state.tenantId) {
            const data = await dataService.getById(id);
            this.set_data(data );
          }
        }
        next();
      });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2021-02-24
    • 2019-10-06
    • 2017-07-25
    • 2017-09-19
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多