首页 > 解决方案 > 如何在页面中的所有内容之前运行js代码?我在 js 中有会话检查,它应该重定向到另一个页面

问题描述

我有会话和 js 检查它是否存在。它工作正常,但仪表板页面可以看到几毫秒,就像眨眼一样。但我需要在加载 html 代码之前重定向网页。我怎样才能做到这一点?我用vue js,连beforeCreate都帮不上忙。

标签: javascripthtmlvue.js

解决方案


就像@Jayem163 在笔记中所说,我将在您的路由器中运行身份验证验证beforeRouteEnter下面是一个基本示例。路由器代码将在组件的任何渲染之前运行。这样您就不会为每条路线提供重复的代码。

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// no authentication required -- OPTIONAL
const noAuthenticationRequired = (to, from, next) => {
  // in my apps right here I force logout. You don't want to go to a login page while logged in. But it's optional
  next()
}

// make sure user is authenticated
const requiresAuthentication = (to, from, next) => {
  // YOUR CHECK AUTH CODE WOULD GO HERE //
  if (success) {
    return next()   
  }

  // not successful
  next('/login')
}

export default new Router({
  routes: [
    {
      path: '/',
      name: 'dashboard',
      beforeEnter: requiresAuthentication, // this route will require authentication
      component: () => import('./views/Dashboard.vue')
    },
    {
      path: '/login',
      name: 'login',
      beforeEnter: noAuthenticationRequired,
      component: () => import('./views/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      beforeEnter: noAuthenticationRequired,
      component: () => import('./views/Register.vue')
    },
    {
      path: '/password/forgot',
      name: 'forgotPassword',
      beforeEnter: noAuthenticationRequired,
      component: () => import('./views/ForgotPassword.vue')
    }
  ]
})

推荐阅读