vue-router#Route TypeScript Examples

The following examples show how to use vue-router#Route. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.ts    From neon with MIT License 6 votes vote down vote up
@Watch('$route', { immediate: false })
  private watchRoute(to: Route) {
    this.menuOpen = false;
    const key = to.path.split('/')[1];
    this.indexModel
      .filter((group) => group.children.find((item) => item.key === key))
      .forEach((group) => {
        group.expanded = true;
        group.children
          .filter((item) => item.key === key)
          .forEach((item) => {
            item.expanded = true;
          });
        group.children = [...group.children];
      });
    this.indexModel = [...this.indexModel];

    setTimeout(() => {
      if (to.hash) {
        const el = document.getElementById(to.hash.substring(1));
        if (el) {
          el.scrollIntoView();
        }
      }
    }, 250);
  }
Example #2
Source File: Source.ts    From neon with MIT License 6 votes vote down vote up
@Watch('$route', { immediate: true })
  private onRoute(to: Route) {
    const path = to.path;
    this.className = path.split('/').pop() || null;
    if (this.className) {
      fetch(`${process.env.VUE_APP_RESOURCE_URL}files/${path}.ts`).then((response) => {
        response.text().then((file) => {
          this.template = file;
        });
      });

      this.ghLink = `https://github.com/aotearoan/neon/tree/master/src/common${path}.ts`;
    }
  }
Example #3
Source File: index.ts    From cli with Apache License 2.0 6 votes vote down vote up
routes: Array<RouteConfig> = [
  {
    path: '/error',
    name: 'Error',
    component: Error,
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    beforeEnter: async (
      _to: Route,
      _from: Route,
      next: NavigationGuardNext<Vue>
    ) => {
      if (!isEnvValid(process.env)) {
        next('/error');
      } else {
        const res = await fetch(getTokenEndpoint());
        const {token} = await res.json();
        // Adding Coveo Headless engine as a global mixin so it can be available to all components
        const engine = getEngine(token);
        Vue.mixin({
          beforeCreate: function () {
            this.$root.$data.$engine = engine;
          },
        });
        next();
      }
    },
  },
]
Example #4
Source File: index.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
VueRouter.prototype.replace = function replace(location: RawLocation): Promise<Route> {
    return new Promise((resolve, reject) => {
        originalReplace.call(
            this,
            location,
            () => {
                // on complete

                resolve(this.currentRoute);
            },
            (error) => {
                // on abort

                // only ignore NavigationDuplicated error
                if (error.name === 'NavigationDuplicated' || error.message.includes('Avoided redundant navigation to current location')) {
                    resolve(this.currentRoute);
                } else {
                    reject(error);
                }
            },
        );
    });
};
Example #5
Source File: permission.ts    From vue-element-typescript-admin with MIT License 5 votes vote down vote up
/**
 * 全局路由拦截
 */
router.beforeEach(async(to: Route, from: Route, next: any) => {
  // Start progress bar
  NProgress.start()

  /**
   *   切换页面把正在发生的请求取消
   *   如果要离开的路由未设置缓存(meta.onCache = true),则必须取消请求
   */
  if (IS_CANCEL_REQUEST_BEFORE_ROUTER_LEAVE || from.meta?.noCache) {
    requestCancelList.forEach((requestCancel, index) => {
      requestCancel.cancel()
      requestCancelList.splice(index, 1)
    })
  }

  // Determine whether the user has logged in
  if (UserModule.token) {
    // 加载store模块
    const [err] = await awaitTo(loadStoreModules())
    if (err) {
      NProgress.done()
      return
    }

    if (to.path === '/account/login') {
      // If is logged in, redirect to the home page
      next({ path: '/home' })
      return
    }

    // Check whether the user has obtained his permission roles
    if (UserModule.roles.length === 0) {
      try {
        // Note: roles must be a object array! such as: ['admin'] or ['developer', 'editor']
        await UserModule.GetUserInfo()
        const roles = UserModule.roles
        // Generate accessible routes map based on role
        PermissionModule.GenerateRoutes(roles)
        // Dynamically add accessible routes
        router.addRoutes(PermissionModule.dynamicRoutes)
        // Hack: ensure addRoutes is complete
        // Set the replace: true, so the navigation will not leave a history record
        next({ ...to, replace: true })
        return
      } catch (err) {
        // Remove token and redirect to login page
        UserModule.ResetToken()
        next(`/account/login?redirect=${to.path}`)
        handleError(err)
        return
      }
    }

    next()
    return
  }

  // Has no token
  if (whiteList.includes(to.path)) {
    // In the free login whitelist, go directly
    next()
    return
  }

  // Other pages that do not have permission to access are redirected to the login page.
  next(`/account/login?redirect=${to.path}`)
})
Example #6
Source File: permission.ts    From vue-element-typescript-admin with MIT License 5 votes vote down vote up
router.afterEach((to: Route) => {
  // Finish progress bar
  NProgress.done()

  // set page title
  document.title = getPageTitle(to.meta.title)
})
Example #7
Source File: index.ts    From cashcash-desktop with MIT License 5 votes vote down vote up
router.beforeEach((to: Route, from: Route, next) => {
    if (to.name !== 'loading-page' && (store as any).state.App.appIsLoading) {
        next({ name: 'loading-page', params: { previousRoutePath: to.path } });
    } else {
        next();
    }
});
Example #8
Source File: ComponentDocumentation.ts    From neon with MIT License 5 votes vote down vote up
@Watch('$route')
  private onRouteChange(to: Route) {
    if (to.hash) {
      this.selected = to.hash.substring(1);
    } else {
      this.selected = this.tabs[0].key;
    }
  }
Example #9
Source File: router.ts    From neon with MIT License 5 votes vote down vote up
router = new VueRouter({
  mode: 'history',
  base: process.env.VUE_APP_BASE_URL,
  routes,
  scrollBehavior: (to: Route, from: Route, savedPosition: void | Position) =>
    to.path !== from.path ? savedPosition || { x: 0, y: 0 } : undefined,
})
Example #10
Source File: router.ts    From neon with MIT License 5 votes vote down vote up
router.afterEach((to: Route) => {
  Vue.nextTick(() => {
    document.title = `Neon: ${
      to.params.enum || to.params.model || to.params.util || to.meta.title || 'A VueJS Component Library'
    }`;
  });
});
Example #11
Source File: beforeEach.ts    From vue-storefront-1 with MIT License 5 votes vote down vote up
export async function beforeEachGuard (to: Route, from: Route, next) {
  if (RouterManager.isRouteProcessing()) {
    await RouterManager.getRouteLockPromise()
    next()
    return
  }
  RouterManager.lockRoute()

  const path = normalizeUrlPath(to.path, false)
  const hasRouteParams = to.hasOwnProperty('params') && Object.values(to.params).length > 0
  const isPreviouslyDispatchedDynamicRoute = to.matched.length > 0 && to.name && to.name.startsWith('urldispatcher')
  if (!to.matched.length || to.matched[0].name.endsWith('page-not-found') || (isPreviouslyDispatchedDynamicRoute && !hasRouteParams)) {
    try {
      const routeData = await UrlDispatchMapper(to)
      if (routeData && !routeData.name.endsWith('page-not-found')) {
        let dynamicRoute: LocalizedRoute = processDynamicRoute(routeData, path, !isPreviouslyDispatchedDynamicRoute)
        if (dynamicRoute) {
          next({
            ...dynamicRoute,
            replace: routerHelper.popStateDetected || dynamicRoute.fullPath === from.fullPath
          })
        } else {
          Logger.error('Route not found ' + routeData['name'], 'dispatcher')()
          next()
        }
      } else {
        Logger.error('No mapping found for ' + path, 'dispatcher')()
        next()
      }
    } catch (e) {
      Logger.error(e, 'dispatcher')()
      next()
    } finally {
      RouterManager.unlockRoute()
    }
  } else {
    next()
    RouterManager.unlockRoute()
    routerHelper.popStateDetected = false
  }

  routerHelper.popStateDetected = false
}
Example #12
Source File: index.ts    From webapp with MIT License 4 votes vote down vote up
router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      setTimeout(() => {
        if (savedPosition) {
          resolve(savedPosition);
        } else {
          resolve({ x: 0, y: 0 });
        }
      }, 500);
    });
  },
  routes: [
    {
      path: "*",
      redirect: `/404`
    },
    {
      path: "/",
      name: "Root",
      redirect: () => {
        const subdomain = detectSubdomain() || "data";
        return `/${defaultModule}/${subdomain}`;
      }
    },
    {
      path: "/404",
      name: "404",
      components: {
        Nav: Navigation,
        default: PageNotFound
      }
    },
    {
      path: "/swap",
      redirect: `/${defaultModule}/swap`
    },
    {
      path: "/swap/:service/swap",
      redirect: `/${defaultModule}/swap`
    },
    {
      path: "/data",
      redirect: `/${defaultModule}/data`
    },
    {
      path: "/data/:service/swap",
      redirect: `/${defaultModule}/swap`
    },
    {
      path: "/vote",
      redirect: `/${defaultModule}/vote`
    },
    {
      path: "/:service/pool/create",
      name: "PoolCreate",
      components: {
        Nav: Navigation,
        Hero: CreateHome
      },
      props: true,
      meta: {
        key: "data",
        feature: "Liquidity"
      }
    },
    {
      path: "/:service/pool/:id",
      name: "PoolAdd",
      components: {
        Nav: Navigation,
        Hero: PoolActionsAddHome
      },
      props: true,
      meta: {
        key: "swap",
        feature: "Liquidity"
      }
    },
    {
      path: "/:service/protection",
      redirect: "/:service/portfolio"
    },
    {
      path: "/:service/pool/:poolAction/:account",
      name: "PoolAction",
      components: {
        Nav: Navigation,
        Hero: PoolActions
      },
      props: true,
      meta: {
        key: "swap",
        feature: "Liquidity"
      }
    },
    {
      path: "/:service/portfolio",
      name: "Portfolio",
      components: {
        Nav: Navigation,
        default: Portfolio
      },
      meta: {
        key: "portfolio",
        feature: "Portfolio"
      }
    },
    {
      path: "/:service/portfolio/whitelistedpools",
      name: "WhitelistedPools",
      meta: {
        key: "portfolio"
      },
      components: {
        Nav: Navigation,
        default: WhitelistedPools
      }
    },
    {
      path: "/:service/portfolio/stake",
      components: {
        Nav: Navigation,
        Hero: ProtectionActions
      },
      props: true,
      meta: {
        key: "portfolio"
      },
      children: [
        {
          path: "",
          name: "ProtectionAction",
          component: AddProtectionHome
        },
        {
          path: "add/single/:id",
          name: "AddProtectionSingle",
          component: AddProtectionSingle
        },
        {
          path: "withdraw/single/:id",
          name: "WithdrawProtectionSingle",
          component: WithdrawProtectionSingle
        },
        {
          path: "rewards/restake/:id",
          name: "RewardsRestake",
          component: RestakeRewards
        },
        {
          path: "rewards/withdraw",
          name: "RewardsWithdraw",
          component: WithdrawRewards
        }
      ]
    },
    {
      path: "/:service/swap",
      components: {
        Nav: Navigation,
        Hero: SwapHome,
        default: LimitOrderTable
      },
      props: true,
      meta: {
        key: "swap",
        feature: "Trade"
      },
      name: "Swap"
    },
    {
      path: "/:service/data",
      components: {
        Nav: Navigation,
        default: Data
      },
      props: true,
      children: [
        {
          path: "",
          name: "Data",
          component: DataSummary,
          meta: {
            key: "data",
            feature: "Data"
          }
        }
      ]
    },
    {
      path: "/:service/vote",
      components: {
        Nav: Navigation,
        default: Vote
      },
      props: true,
      children: [
        {
          path: "",
          name: "Vote",
          component: VotePage,
          meta: {
            key: "vote",
            feature: "Vote"
          }
        }
      ]
    },
    {
      path: "/:service/vote-legacy",
      components: {
        Nav: Navigation,
        default: Vote
      },
      props: true,
      children: [
        {
          path: "",
          name: "VoteLegacy",
          component: VoteLegacy,
          meta: {
            key: "vote",
            feature: "Vote"
          }
        }
      ]
    },
    {
      path: "/:service/fiat",
      name: "Fiat",
      components: {
        Nav: Navigation,
        default: Fiat
      },
      props: true,
      children: [
        {
          path: "",
          name: "FiatPage",
          component: FiatPage,
          meta: {
            key: "fiat",
            feature: "Fiat"
          }
        }
      ]
    },
    {
      path: "/:service",
      props: true,
      redirect: (to: Route) => {
        if (to.params.service == ethService.namespace) {
          return `/${ethService.namespace}/swap`;
        }
        return "/404";
      }
    },
    {
      path: "/privacy-policy",
      name: "PrivacyPolicy",
      components: {
        Nav: Navigation,
        default: PrivacyPolicy
      }
    },
    {
      path: "/terms-of-use",
      name: "TermsOfUse",
      components: {
        Nav: Navigation,
        default: TermsOfUse
      }
    },
    {
      path: "*",
      redirect: `/${defaultModule}`
    },
    {
      path: "/",
      redirect: () => {
        return `/${defaultModule}/swap`;
      }
    }
  ]
})