vue.js - 根据路由参数在启动时加载 Vuex 状态
问题描述
我有一个 Vue 应用程序,其中包含许多具有tenantId
参数的路由。第一次加载应用程序时,我必须tenantId
从路由中获取值,从 API 加载数据并用它初始化 Veux 存储。
我不应该显示任何路由器视图组件,因为它假定初始状态已经加载。
所以,我试图在没有运气的钩子中实现它App.vue
created
,因为在那个阶段是空的。不要求。在模块内部,我没有对商店的引用。mounted
$route
beforeRouteEnter
App.vue
beforeEach
router
这种初始化的正确位置是什么?
解决方案
您可以在您的app.js
ormain.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
})
推荐阅读
- python - 如何使用 Django 编辑 html 页面并将其保存在同一页面中?
- matplotlib - 如何在 matplotlib 中绘制简单的太阳之类的东西?
- electron - 以编程方式检测安装类型
- vbscript - 如何在 VBS 的 WMI 服务查询中使用变量名
- r - 数据框不会在 Shiny R 中使用 observeEvent 更新
- django - Django + Mongo + Docker 得到 pymongo.errors.ServerSelectionTimeoutError
- powershell - 是否可以使用 powershell 或批处理文件以不同的名称重命名文件夹中的每个文件?
- c# - 在 Windows 窗体应用程序 C# 中使用 Windows 服务应用程序
- python - 从python中的网页中提取电子邮件
- pytorch - CNN:准确率和损失在增加和减少