Doesn't work redirect in beforeEnter(Vue)Heeeelp :c

When I want to load a component with tabs, I want to redirect to a specific tab, but this does not work.
Please, help me
main.vue

  <!-- View for Single Activity -->
  <f7-view
v-if="meetupType === 'single_activity' && meetupLoaded"
id="main-view"
:router="true"
:routes="SingleActivityRoutes"
:push-state="true"
:animate="isWebApp"
:ios-swipe-back="isWebApp"
main
url="/" />

  <!-- View for Themed Schedule -->
  <f7-view
v-else-if="meetupType === 'themed' && meetupLoaded"
id="main-view"
:router="true"
:routes="ThemedRoutes"
:push-state="true"
:animate="isWebApp"
:ios-swipe-back="isWebApp"
main
url="/" />

  <!-- View for Full Schedule -->
  <f7-view
v-else-if="meetupType === 'scheduled' && meetupLoaded"
id="main-view"
:router="true"
:routes="ScheduledRoutes"
:push-state="true"
:animate="isWebApp"
:ios-swipe-back="isWebApp"
main
url="/" />

  <!-- Page Loader -->
  <div v-else>
<loader />
  </div>

single-activity.js

    export default [
  {
    path: "/",
    component: MainPage,
    beforeEnter: (routeTo, routeFrom, resolve, reject) => {
      for (var key in store.state.activities) {
        var activity = store.state.activities[key];
      }
      if (activity.tab_files && !activity.tab_question && !activity.tab_poll) {
        resolve({
          path: "/",
          id: "questions",
          component: QuestionsPage
        })
      } else if (
        !activity.tab_files &&
        !activity.tab_question &&
        activity.tab_poll
      ) {
        reject();
      } else {
        reject();
      }
    },
    tabs: [
      {
        path: "/",
        id: "questions",
        component: QuestionsPage
      },
      {
        path: "/questions/",
        id: "questions",
        component: QuestionsPage
      },
      {
        path: "/polls/",
        id: "polls",
        component: PollsPage
      },
      {
        path: "/materials/",
        id: "materials",
        component: MaterialsPage
      }
    ]
  },
  {
    path: "/event/:scheduleId/:eventId/:itemId/question/:questionId",
    popup: {
      component: QuestionPage
    }
  },
  {
    path: "/:eventId/questions/:scheduleId/:questionId/:itemId/",
    redirect: (
      { params: { scheduleId, eventId, itemId, questionId } },
      resolve
    ) =>
      resolve(
        `/event/${scheduleId}/${eventId}/${itemId}/question/${questionId}`
      )
  },
  {
    path: "/event/:scheduleId/:eventId/:itemId/poll/:pollId",
    popup: {
      component: PollPage
    }
  },
  {
    path: "/:eventId/polls/:scheduleId/:pollId/:itemId/",
    redirect: ({ params: { scheduleId, eventId, itemId, pollId } }, resolve) =>
      resolve(`/event/${scheduleId}/${eventId}/${itemId}/poll/${pollId}`)
  },
  {
    path: "/event/:scheduleId/:eventId/:itemId/slidepresentation/",
    component: SlidePresentationPage
  },
  {
    path:
      "/event/:scheduleId/:eventId/:itemId/slidepresentation/:questionId/comments/",
    popup: {
      component: CommentsPage
    }
  },
  {
    path: "(.*)",
    component: NotFoundPage
  }
]

Use (_,_,resolve, reject). if a condition is not met,
reject and then redirect to another path like:

reject();
router.navigate('/some-path-after-reject/');

How i can call entity router in single-activity.js?

`{

path: ‘/some-path/’,

beforeEnter(routeTo, routeFrom, resolve, reject){

const router = this;

const app = router.app

}
}`

That should do…

But there is no access to this in the routes files.

Зачем вам нужен доступ к this?

Мне Max посоветовал в предыдущем комментарии использовать this для доступа к приложению, чтобы была возможность обратиться к router и перенаправить на другой маршрут. Но я думаю, что это не будет работать. Вы знаете как перенаправить на другой маршрут в beforeEnter?

  1. Лучше использовать async для этого.
  2. Роутер привязан к каждому view, а не к экземпляру приложения.
  3. Можно всегда обратится к глобальной переменой app

А как я могу обратиться к глобальной app?

app.views.current.router

При использовании в файле c путями -> app.views undefined
И при запросе app мне возвращается просто NodeList

А, вы используете Vue, просмотрел. Тогда вам стоит подождать ответ от тех, кто работает с Vue.

Принял :disappointed_relieved:

this should point to the current router object.
Try to console log it and see

in BeforeEnter console.log(this) -> undefined

А где собственно редирект внутри beforeEnter? Не вижу, или имеется ввиду resolve который там? Что именно не работает в роутах?

Вообще, вопрос как из beforeEnter редиректнуть, ну и при передаче в resolve компонента, ничего не происходит

Так

beforeEnter(to, from, resolve, reject) {
  const router = this;
  if (/* need redirect */) {
    reject();
    router.navigate('/another-path/');
    return;
  }
  resolve();
}
1 Like

beforeLeave / beforeEnter не принимают никаких параметров в resolve(), эти коллбэки только предназначены для того чтобы разрешить/запретить переход на роут, они не позволяют модифицировать параметры роута. Используйте тогда async() вместо этого.