javascript - 如何在页面中的所有内容之前运行js代码?我在 js 中有会话检查,它应该重定向到另一个页面
问题描述
我有会话和 js 检查它是否存在。它工作正常,但仪表板页面可以看到几毫秒,就像眨眼一样。但我需要在加载 html 代码之前重定向网页。我怎样才能做到这一点?我用vue js,连beforeCreate都帮不上忙。
解决方案
就像@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')
}
]
})
推荐阅读
- spring - 用于使用列表访问 json 的 Spring 表达式语言 (SpEL)
- node.js - AES 128 ECB 解密 nodejs
- flutter - 直到版本 2.2 才支持设置文字
- android - 使用“info.hoang8f.widget.FButton”的问题
- javascript - 如何从json字符串中递归获取父ID
- magento2 - 如何在 magento 2 中为我的所有帐户页面设置相同的页面标题?
- jquery - HTML 表格嵌套选择器
- python - 如何从需要用户名和密码的网站获取授权承载来测试 API?
- objective-c - 在开始时声明时继续使用未声明的标识符
- javascript - 添加 ng-controller 会停止 AngularJS