首页 > 解决方案 > 根据路由参数在启动时加载 Vuex 状态

问题描述

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

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

所以,我试图在没有运气的钩子中实现它App.vue created,因为在那个阶段是空的。不要求。在模块内部,我没有对商店的引用。mounted$routebeforeRouteEnterApp.vuebeforeEachrouter

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

标签: vue.jsvuexvue-router

解决方案


您可以在您的app.jsormain.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
})

推荐阅读