首页 > 解决方案 > 使用 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 文件中,我认为这不是很漂亮。

有没有解决这个问题的最佳实践?

我很感激一个提示,谢谢。

标签: javascriptvue.jsvue-router

解决方案


使用 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) {

推荐阅读