Use vue-router navigation guard to implement token login page jump

If you don’t understand anything, please message me privately!!!

1 Introduction

Requirements introduction

This time is the process of realizing a simple login page to jump to multiple pages. The jump page also comes with some conditions: 1.
Store the token every time you log in.
2. Clear the token every time you log in and out
. 3. Prevent modification of the URL. The hash parameter is used to access the backend homepage. The navigation guard beforeEach is used here to detect whether there is a token in the local storage. If there is a token, you can access the backend homepage. If not, you cannot.

2 main knowledge points

2.1 Navigation Guard

Every time a routing navigation jump occurs, the global pre-guard will be triggered. There are 3 formal parameters
A->C
1. The to function is the routing object C that will be accessed
2. The from function is the routing object A that will be left
3.next The function indicates release

   // 只要发生了路由的跳转 必然会触发beforeEach指定的function回调函数
   router.beforeEach((to,from,next)=>{
    
    
   	//需要检查是否登录的白名单
   	const pathArr=[
   	'/home',
   	'/home/yonghu',
   	'/home/quanxian',
   	'/home/shangpin',
   	'/home/dingdan',
   	'/home/xitong',
   	'/home/userinfo'
   ]
   
   	// A->C
   // to函数是将要访问的路由对象 C
   // from函数是将要离开路由对象   A
   // next函数表示放行
   // 分析
   // 1.要拿到用户将要访问的hash地址
   // 2.判断hash地址是否等于/Main
   // 2.1.如果等于/Main.证明要登录之后,才能访问成功
   // 2.2.如果不等于/Main,则不需要登录,直接放行next()
   // 3.如果访问的地址时/Main,则需要读取localStorage中的token值
   // 3.1如果有token,则放行
   // 3.2如果没有token,则强制跳转到/login登录页
   
   	// 要是多个页面都需要token检测
   	// 找to.path在不在这个pathArr数组里面,要是等于-1就是不在,不等于-1就是在
   	if(pathArr.indexOf(to.path) !== -1){
    
    
   		// 要访问后台主页,需要判断是否有token
   		const token=localStorage.getItem('token')
   		if(token){
    
    
   			next()
   		}else{
    
    
   			next('/login')
   		}
   	}else{
    
    
   		next()
   	}
   })

2.2 Storage setting token

Call the submit method through the click event when logging in

		submit(username,password){
    
    
			console.log(username);
			console.log(password);
			if(username=='123' && password=='123'){
    
    
				// 登录成功存储设置token
				localStorage.setItem('token','whl 123123')
				console.log('登录成功');
				this.$router.push('/home')
			}else{
    
    
				// 登陆失败清除toekn
				localStorage.removeItem('token')
				console.log('登录失败');
			}
		},

2.3 Clear token

	localStorage.removeItem('token')

2.4 Get token

	const token=localStorage.getItem('token') //获取之后,用token变量进行接收
	console.log(token)

3 other important knowledge points

3.1 Programmatic Navigation API

In a browser, the method of calling API methods to implement navigation is called programmatic navigation. For example:
⚫ The method of calling location.href to jump to a new page in an ordinary web page belongs to programmatic navigation
⚫ vue-router provides many programmatic navigation APIs, among which the most commonly used navigation APIs are:

	⚫ 跳转到指定 hash 地址,并增加一条历史记录
	this.$router.push('hash地址') //这里的hash地址就是router文件夹下index.js跟组件的对应关系
	⚫ 跳转到指定的 hash 地址,并替换掉当前的历史记录
	this.$router.replace('hash地址')
	⚫ 实现导航历史前进、后退
	this.$router.go(数值 n)
	//在实际开发中,一般只会前进和后退一层页面。因此 vue-router 提供了如下两个便捷方法:
	⚫ 在历史记录中,后退到上一个页面
	this.$router.back()
	⚫ 在历史记录中,前进到下一个页面
	this.$router.forward()

3.2 Nested routing

Insert image description here
1.router-view: As long as vue-router is installed and configured in the project, you can use the vue-router component (placeholder)

	<router-view></router-view>

2.router-link: After installing vue-router, you can use router-link instead of a link

	<a href="#/movie">电影</a>
	<router-link to="/movie">电影</router-link>

3. What should be noted here is that the first router-view and the second router-view have no connection. It can be understood that the first one is in the parent component, the second one is in the child component, and they are in different pages. Call router-link to use router-view to display different content

	<router-link to="/about">tab1</router-link>  //children的path为空,叫做默认子路由,{path:'',component:Tab1}
	<router-link to="/about/tab2">tab2</router-link>
	<hr>
	<router-view></router-view>
	//src.router.index.js是当前项目的路由模块
	
	// 1.导包
	import Vue from 'vue'
	// VueRouter是构造函数,要new实例
	import VueRouter from 'vue-router'
	import Home from '@/components/Home.vue'
	import Movie from '@/components/Movie.vue'
	import About from '@/components/About.vue'
	import Tab1 from '@/components/tabs/Tab1.vue'
	import Tab2 from '@/components/tabs/Tab2.vue'
	
	
	//2.调用vue.use()给vue装插件,把VueRouter安装为vue插件
	Vue.use(VueRouter)
	
	// 3.创建路由的实例对象
	const router=new VueRouter({
    
    
		// routes是一个数组,作用定义"hash地址"与"组件"之间的关系
		routes:[
			//路由规则
			// 当用户访问 / 的时候,通过redirect跳转到/home对应的路由规则
			{
    
    path:'/',redirect:'/home'},
			{
    
    path:'/home',component:Home},
			{
    
    path:'/movie',component:Movie},
			{
    
    
				//about页面的路由规则(父级路由规则)
				path:'/about',
				component:About,
				// 通过children嵌套声明子级路由的规则
				children:[
					//默认子路由:如果children数组中,某个路由的规则的path空值
					// 为空字符串,则这条路由规则,叫做”默认子路由“
					{
    
    path:'',component:Tab1},
					{
    
    path:'tab2',component:Tab2}
				]
			},
		]
	})
	
	// 4.向外共享路由的实例对象
	export default router

3.3 Dynamic routing

Define the variable part of the hash address as a parameter item to improve the reusability of the rules

For example, the project allows you to develop a product and product details page. Click the details button to jump to the product details page. At this time, dynamic routing is used. In addition to being simple and easy to use, the greater role is to enable product details. The page obtains different IDs, so each product details page obtains different product data.

	{
    
    path:'/movie/:id',component:Movie},

Insert image description here

3.3.1 Transfer data to router

	<a href="#" @click.prevent="xiangqing(item.id)">详情</a>
		
	xiangqing(id){
    
    
		this.$router.push('/home/userinfo/'+id)
	}	
	

3.3.2 Router receives via:id

	const router = new VueRouter({
    
    
		// path里面的hash地址不能够是大写
		routes:[
			// redirect重定向/login,再指向component的
			// Login渲染到router-view
			{
    
    path:'/',redirect:'/login'},
			{
    
    path:'/login',component:Login},
			{
    
    	
				path:'/home',
				component:Home,
				redirect:'/home/yonghu',
				children:[
					// 要是子路由中,某个path为空值,默认子路由(默认展示)
					// children不需要添加/
					{
    
    path:'yonghu',component:MyUsers},
					{
    
    path:'quanxian',component:MyRights},
					{
    
    path:'shangpin',component:MyGoods},
					{
    
    path:'dingdan',component:MyOrders},
					{
    
    path:'xitong',component:MySettings},
					// :id主要租用就是;因为是详情,就通过id来进行区分
					{
    
    path:'userinfo/:id',component:MyUserDetail,props:true},
				]
			},
		
		]
	})

3.3.2 Get $route parameter object

3.3.2.1 this.$route.params

Use it directly under the corresponding method

	{
    
    {
    
    this.$route.params.id}} //1,2,3
3.3.2.2 Passing parameters via props

Premise: In the router correspondence, props: true must be turned on and the code above has been written.

	props:['id'] //进行注册
	{
    
    {
    
    id}} //使用
	props:true //router对应关系中一定要开启

4 indexOf

indexOf is used in the navigation guard

4.1 Array call

If the condition is not met, -1 is returned.

	let food= ["1", "2", "3", "4"];
	let a = food.indexOf("4");
	console.log(a) // 3
	let b= food.indexOf("5");
	console.log(b) // -1

4.2 String call

Returns the first occurrence of a specified string value in the string, case-sensitively

	let str="Hello world!";
	console.log(str.indexOf("Hello"));//0
	console.log(str.indexOf("world"));//6
	console.log(str.indexOf("World") );//-1

5 renderings

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/m0_62496369/article/details/127498147