javascript - 使用 vue 和 vue-router 确保视图顺序的最佳实践
问题描述
我用 Vue 创建了一个带有一些不同视图/组件的应用程序。视图/组件必须以特定顺序运行(MainPage -> Step1 -> Step2 -> Step3 -> FinalPage --> MainPage...)。
在学习 Vue 时,我使用 v-if 指令管理导航,该指令运行良好,因为没有 URL,因此我能够在每个视图/组件中实现逻辑,例如
//pseudocode in each view/component
checkConditionsToMoveOn ? moveToNextPae : showErrorWithModalAndStayOnPage;
变得更加专业,我实现了 vue-router,它以某种方式破坏了我的应用程序,因为我现在能够通过手动更改 URL 来欺骗逻辑以通过一个步骤。
我可以考虑实现一些导航保护,但是我必须将条件移动到我的 router/index.js 文件中,我认为这不是很漂亮。
有没有解决这个问题的最佳实践?
我很感激一个提示,谢谢。
解决方案
使用 Vuex,跟踪 step 进度的当前状态:
state: {
step: 1
}
当用户访问任何步骤时,您将检查此状态。如果请求的步骤路线与此不匹配,您将重定向到它。要实现这一点,请使用route params定义路由:
// import store from '@/store';
{
path: '/step/:sid',
name: 'step',
component: Step,
...
现在您可以将您的应用定向到类似http://localhost:8080/step/5
. 该变量to.params.sid
将匹配该5
路线中的 。因此,在beforeEnter
警卫中,检查参数是否与商店的步骤匹配。
...
beforeEnter: (to, from, next) => {
const nextStep = parseInt(to.params.sid); // convert string param to number
if (nextStep === store.state.step) { // is this the current allowed step?
next(); // if so, it's ok
} else { // if not, direct to that step
next({ name: 'step', params: { sid: store.state.step }})
}
}
},
每当一个步骤完成时,您将增加存储步骤,然后将路由器引导到下一步。
额外的:
您还可以更改if
条件以允许访问之前的步骤:
if (nextStep > 0 && nextStep <= store.state.step) {
推荐阅读
- python - Python exe脚本无法运行
- javascript - 为什么我不能使用 location.reload 作为回调?
- javascript - 使用带有类型定义的 const 创建组件时没有警告 - ReactJS+Typescript
- python - gRPC python发送图像+元数据
- php - 使用苗条框架时未执行 PHP 代码(已注释掉)
- windows-10 - pyinstaller 包获取 UnicodeDecodeError: 'utf-8' codec can't decode byte
- webrtc - 如何删除 Ant Media Server 中录制的自适应 mp4 文件?
- kubernetes - 缺少更改 Kubernetes 部署 yaml 以获取容忍文档
- powershell - 如何在 WMI 查询中使用 LIKE 运算符?
- c# - How to improve algorithm for transforming dot separated strings to data objects?