vue-router#Router TypeScript Examples

The following examples show how to use vue-router#Router. 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: auth.ts    From quasar-app-extension-http-authentication with MIT License 6 votes vote down vote up
useLogin = ({ router }: { router?: Router} = {}) => {
  /**
   * Replace with your own function
   */
  const $q = useQuasar()
  const lang = useLang()
  const loading = ref(false)
  const result = ref()
  const fetch = (user: Ref<unknown>, rememberMe?: boolean) => {
    loading.value = true
    return new Promise<{ user: Record<string, unknown>, token: string }>((resolve, reject) => {
      setTimeout(() => {
        resolve({
          user: {
            email: '[email protected]',
            roles: []
          },
          token: 'token'
        })
      }, 1000)
    }).then((res) => {
      result.value = res
      const { user, token } = res
      setUser(user)
      // setHeader() -- e.g. axios.defaults.headers.common.Authorization = `Bearer ${token}`
      setTokenCookie($q, token, rememberMe)
      return res
    }).catch((res: unknown) => {
      if (res === '401') return verificationRequiredDialog($q, {}, lang)
      if (res === '403') return invalidCredentialsDialog($q, {}, lang)
    }).finally(() => {
      loading.value = false
    })
  }

  return { result, loading, fetch }
}
Example #2
Source File: auth.ts    From quasar-app-extension-http-authentication with MIT License 6 votes vote down vote up
useLogout = ({ router }: { router: Router}) => {
  /**
   * Replace with your own function
   */
  const $q = useQuasar()
  const lang = useLang()

  const logout = () => logoutDialog($q, {
    onOk: () => router.push('/')
  }, lang)

  return logout
}
Example #3
Source File: auth.ts    From quasar-app-extension-http-authentication with MIT License 6 votes vote down vote up
useRegister  = ({ router }: { router?: Router} = {}) => {
  /**
   * Replace with your own function
   */
  const $q = useQuasar()
  const lang = useLang()
  const loading = ref(false)
  const result = ref()
  const fetch = (user: Ref<unknown>) => {
    loading.value = true
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('200')
      }, 1000)
    }).then((res: unknown) => {
      result.value = res
      return res
    }).catch((res: unknown) => {
      if (res === '403') return invalidDataDialog($q, {}, lang)
      if (res === '409') return alreadyRegisteredDialog($q, {}, lang)
      return registrationErrorDialog($q, {}, lang)
    }).finally(() => {
      loading.value = false
    })
  }

  return { result, loading, fetch }
}
Example #4
Source File: auth.ts    From quasar-app-extension-http-authentication with MIT License 6 votes vote down vote up
usePasswordForgot = ({ router }: { router?: Router} = {}) => {
  /**
   * Replace with your own function
   */
  const $q = useQuasar()
  const lang = useLang()
  const loading = ref(false)
  const result = ref()
  const fetch = (user: Ref<unknown>) => {
    loading.value = true
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('200')
      }, 1000)
    }).then((res: unknown) => {
      result.value = res
      checkEmailDialog($q, {
        onOk: () => router?.push('/login')
      }, lang)
      return res
    }).catch((res: unknown) => {
      return unknownEmailDialog($q, {}, lang)
    }).finally(() => {
      loading.value = false
    })
  }

  return { result, loading, fetch }
}
Example #5
Source File: auth.ts    From quasar-app-extension-http-authentication with MIT License 6 votes vote down vote up
usePasswordReset = ({ router }: { router?: Router} = {}) => {
  /**
   * Replace with your own function
   */
  const $q = useQuasar()
  const lang = useLang()
  const loading = ref(false)
  const result = ref()
  const fetch = (user: Ref<unknown>, token: string) => {
    loading.value = true
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('200')
      }, 1000)
    }).then((res: unknown) => {
      result.value = res
      passwordResetSuccessDialog($q, {
        onOk: () => router?.push('/login')
      }, lang)
      return res
    }).catch((res: unknown) => {
      console.error(res)
    }).finally(() => {
      loading.value = false
    })
  }

  return { result, loading, fetch }
}
Example #6
Source File: auth.ts    From quasar-app-extension-http-authentication with MIT License 6 votes vote down vote up
useVerify = ({ router }: { router?: Router} = {}) => {
  /**
   * Replace with your own function
   */
  const $q = useQuasar()
  const lang = useLang()
  const loading = ref(false)
  const result = ref()
  const fetch = (token: string) => {
    loading.value = true
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('200')
      }, 1000)
    }).then((res: unknown) => {
      result.value = res
      verificationSuccessDialog($q, {
        onOk: () => router?.push('/login')
      }, lang)
      return res
    }).catch((res: unknown) => {
      return verificationFailedDialog($q, {}, lang)
    }).finally(() => {
      loading.value = false
    })
  }

  return { result, loading, fetch }
}
Example #7
Source File: index.ts    From code996 with The Unlicense 5 votes vote down vote up
function changeTitleGuide(router: Router) {
  router.beforeEach((to, from, next) => {
    const title = to.meta.title as string
    document.title = title
    next()
  })
}
Example #8
Source File: router.ts    From vue-i18n-next with MIT License 5 votes vote down vote up
export function setupRouter(i18n: I18n): Router {
  const locale = getLocale(i18n)

  // setup routes
  const routes: RouteRecordRaw[] = [
    {
      path: '/:locale/',
      name: 'home',
      component: Home
    },
    {
      path: '/:locale/about',
      name: 'about',
      component: About
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: () => `/${locale}`
    }
  ]

  // create router instance
  const router = createRouter({
    history: createWebHistory(),
    routes
  })

  // navigation guards
  router.beforeEach(async to => {
    const paramsLocale = to.params.locale as string

    // use locale if paramsLocale is not in SUPPORT_LOCALES
    if (!SUPPORT_LOCALES.includes(paramsLocale)) {
      return `/${locale}`
    }

    // load locale messages
    if (!i18n.global.availableLocales.includes(paramsLocale)) {
      await loadLocaleMessages(i18n, paramsLocale)
    }

    // set i18n language
    setI18nLanguage(i18n, paramsLocale)
  })

  return router
}
Example #9
Source File: helpers.ts    From quasar-app-extension-http-authentication with MIT License 5 votes vote down vote up
export function setRouteGuard (
  { router, loggedIn, fetchUser, checkUserRoles }:
  { router: Router, loggedIn: (requiredRoles?: string[]) => boolean, fetchUser: (requiredRoles?: string[]) => Promise<void>, checkUserRoles: (record: string[]) => boolean }
  ){
  router.beforeEach((to, from, next) => {
    const requiresAuth = to.matched.find(record => record.meta.requiresAuth)?.meta.requiresAuth
    const requiredRoles = to.matched.find(record => record.meta.requiredRoles)?.meta.requiredRoles
    const unauthenticatedRouteLocation = to.matched.find(record => record.meta.unauthenticatedRouteLocation)?.meta.unauthenticatedRouteLocation
    const unauthorizedRouteLocation = to.matched.find(record => record.meta.unauthorizedRouteLocation)?.meta.unauthorizedRouteLocation

    // const checkAuthorization = () => {
    //   if (!loggedIn()) {
    //     return fetchUser().then(() => {
    //       if (!loggedIn()) return next('/')
    //       if (requiredRoles && checkUserRoles && !checkUserRoles(requiredRoles)) return next({ name: 'account' })
    //       return next()
    //     }).catch(() => {
    //       return next('/')
    //     })
    //   }
    //   if (requiredRoles && checkUserRoles && !checkUserRoles(requiredRoles)) return next({ name: 'account' })
    //   next()
    // }

    if (requiresAuth) {
      if (!loggedIn(requiredRoles)) {
        return fetchUser(requiredRoles).then(() => {
          if (!loggedIn(requiredRoles)) return next(unauthenticatedRouteLocation || '/')
          if (requiredRoles && checkUserRoles && !checkUserRoles(requiredRoles)) return next(unauthorizedRouteLocation || { name: 'account' })
          return next()
        }).catch(() => {
          return next(unauthenticatedRouteLocation || '/')
        })
      }
      if (requiredRoles && checkUserRoles && !checkUserRoles(requiredRoles)) return next(unauthorizedRouteLocation || { name: 'account' })
    }

    next()
  })
}