目录

一,vue-router路由

二,vue-router路由常用配置

三,vue-router路由嵌套

四,vue-router路由参数传递与获取

五,使用props替代路由对象获取参数

六,路由的动态跳转

七,路由&过渡


一,vue-router路由

vue-router路由:Vue.js官网推出的路由管理器,方便的构建单页应用;

单页应用:Single Page Application简称SPA,只有一个web页面的应用,用户与应用交互时,动态更新该页面的内容;

                  简单的来说,根据不同的url与数据,将他们都显示在同一个页面中,就可以称为是单页应用;

                  而控制页面跳转需要用路由;

vue-router官网:点击前往

vue-router下载:下载js,或使用npm install vue-router -S

vue-router使用:

  1. 定义组件;
  2. 配置路由;
  3. 创建路由对象;
  4. 注入路由;
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>01_vue-router</title>
	</head>
	<body>
		<div id="sikiedu">
			<router-link to="/home">首页</router-link>
			<router-link to="/foods">美食</router-link>
			
			<div>
				<!--将数据显示在这里-->
				<router-view></router-view>
			</div>
		</div>
	</body>
	
	<script type="text/javascript" src="../js/vue.js" ></script>
	<script type="text/javascript" src="../js/vue-router.js" ></script>
	<script>
		
		//1 定义组件
		let Home = {
			template : "<h2>首页</h2>"
		}
		let Foods = {
			template : "<h2>美食</h2>"
		}
		
		//2 配置路由 路由可能有多个
		const myRoutes = [
			{
				path : "/home",
				component : Home
			},
			{
				path : "/foods",
				component : Foods
			}
		]
		
		// 3 创建路由对象
		const myRouter = new VueRouter({
			routes : myRoutes
		});
		
		new Vue({
			router : myRouter //4 注入路由 简写
		}).$mount("#sikiedu");
	</script>
</html>

 

二,vue-router路由常用配置

mode:配置路由模式,默认为hashURL很丑,可以修改为history,但是需要服务端的支持;

redirect:重定向,可以设置默认页面;

linkActiveClass:设置router-link激活样式;

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>02_vue-router_config</title>
		
		<style type="text/css">
			.active{
				color: #FFFFFF;
				background-color: red;
		}
		
	</style>
	</head>
	<body>
		<div id="sikiedu">
			<router-link to="/home">首页</router-link>
			<router-link to="/foods">美食</router-link>
			
			<div>
				<!--将数据显示在这里-->
				<router-view></router-view>
			</div>
		</div>
	</body>
	
	<script type="text/javascript" src="../js/vue.js" ></script>
	<script type="text/javascript" src="../js/vue-router.js" ></script>
	<script>
		
		//1 定义组件
		let Home = {
			template : "<h2>首页</h2>"
		}
		let Foods = {
			template : "<h2>美食</h2>"
		}
		
		//2 配置路由 路由可能有多个
		const myRoutes = [
			{
				path : "/home",
				component : Home
			},
			{
				path : "/foods",
				component : Foods
			},
			{
				path : "*",
				redirect : "/home"
			}
		]
		
		// 3 创建路由对象
		const myRouter = new VueRouter({
			//routes : routes
			routes : myRoutes,
			mode: 'history' ,
			linkActiveClass : "active"
		});
		
		new Vue({
			//router : router
			router : myRouter //4 注入路由 简写
		}).$mount("#sikiedu");
	</script>
	
</html>

 

三,vue-router路由嵌套

路由的嵌套:一个路由中嵌套(包含)其他的路由;

在路由的配置中,使用children可以配置子路由,children也可以配置多个,与routes一致;

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>03_vue-router_nested</title>
		
		<style type="text/css">
			.active{
				color: #FFFFFF;
				background-color: red;
		}
	</style>
	</head>
	<body>
		<div id="sikiedu">
			<router-link to="/home">首页</router-link>
			<router-link to="/foods">美食</router-link>
			
			<div>
				<!--将数据显示在这里-->
				<router-view></router-view>
			</div>
		</div>
	</body>
	
	<template id="foods">
		<div>
			<h2>美食广场</h2>
			<ul>
				<router-link to="/foods/bjc" tag="li">北京菜</router-link>
				<router-link to="/foods/scc" tag="li">四川菜</router-link>
				<router-link to="/foods/xc"  tag="li">湘菜</router-link>
				<router-link to="/foods/yc"  tag="li">粤菜</router-link>
			</ul>
			
			<router-view></router-view>
		</div>
	</template>
	
	<script type="text/javascript" src="../js/vue.js" ></script>
	<script type="text/javascript" src="../js/vue-router.js" ></script>
	<script>
		
		//1 定义组件
		let Home = {
			template : "<h2>首页</h2>"
		}
		let Foods = {
			template : "#foods"
		}
		
		//定义foods中的子组件
		let Bjc = {
			template : "<h3>北京菜</h3>"
		}
		let Scc = {
			template : "<h3>四川菜</h3>"
		}
		let Xc = {
			template : "<h3>湘菜</h3>"
		}
		let Yc = {
			template : "<h3>粤菜</h3>"
		}
		
		//2 配置路由 路由可能有多个
		const myRoutes = [
			{
				path : "/home",
				component : Home
			},
			{
				path : "/foods",
				component : Foods,
				children : [
					{
						path : "bjc",
						component : Bjc
					},
					{
						path : "scc",
						component : Scc
					},
					{
						path : "xc",
						component : Xc
					},
					{
						path : "yc",
						component : Yc
					}
				]
			},
			{
				path : "*",
				redirect : "/home"
			}
		]
		
		// 3 创建路由对象
		const myRouter = new VueRouter({
			routes : myRoutes,
			linkActiveClass : "active"
		});
		
		new Vue({
			router : myRouter //4 注入路由 简写
		}).$mount("#sikiedu");
	</script>
	
	
</html>

 

四,vue-router路由参数传递与获取

使用路由对象$route获取参数:

  1.params

         a.参数传递:

                 a)URL传参:例 <route-linke to : "/foods/bjc/北京烤鸭/68">   注:在对应路由path上使用 /:+属性名称接收参数

                 b)对象传参:例 <route-linke :to : "xxObj"> 注:对象格式{String name, Objce param} name是路由名称,param是传                                          递参数的对象

         b. 参数获取:使用$route.params获取参数;

   2.query

         a.参数传递:

                a)URL传参:例 <route-linke to : "/foods/bjc?name=北京烤鸭&price=68">

                b)对象传参:例 <route-linke :to : "xxObj"> 注:对象格式{String path, Objce query} path是路由urlquery是传递参数                                          的对象

        b.参数获取:使用$route.query获取参数;

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>04_vue-router_passing_props</title>
		<style type="text/css">
			.active{
				color: #FFFFFF;
				background-color: red;
			}
		</style>
	</head>
	<body>
		<div id="sikiedu">
			<router-link to="/home">首页</router-link>
			<router-link to="/foods">美食</router-link>
			
			<div>
				<!--将数据显示在这里-->
				<router-view></router-view>
			</div>
		</div>
	</body>
	
	<template id="foods">
		<div>
			<h2>美食广场</h2>
			<ul>
				<router-link to="/foods/bjc/北京烤鸭/68" tag="li">北京菜</router-link>
				<router-link :to="sccParam" tag="li">四川菜</router-link>
				<router-link to="/foods/xc?name=剁椒鱼头&price=128"  tag="li">湘菜</router-link>
				<router-link :to="ycParam"  tag="li">粤菜</router-link>
			</ul>
			
			<router-view></router-view>
		</div>
	</template>
	
	<script type="text/javascript" src="../js/vue.js" ></script>
	<script type="text/javascript" src="../js/vue-router.js" ></script>
	<script>
		
		//1 定义组件
		let Home = {
			template : "<h2>首页</h2>"
		}
		let Foods = {
			template : "#foods",
			data(){
				return {
					sccParam : {
						name : 'sccRouter',
						params : {
							name : '麻婆豆腐',
							price : 28
						}
					},
					ycParam : {
						path : '/foods/yc',
						query : {
							name : '蜜汁叉烧',
							price : 56
						}
					}
				}
			}
		}
		
		//定义foods中的子组件
		let Bjc = {
			template : "<h3>北京菜 菜名 : {{$route.params.name}} 价格 : {{$route.params.price}}</h3>"
		}
		let Scc = {
			template : "<h3>四川菜 菜名 : {{$route.params.name}} 价格 : {{$route.params.price}}</h3>"
		}
		let Xc = {
			template : "<h3>湘菜 菜名 : {{$route.query.name}} 价格 : {{$route.query.price}}</h3>"
		}
		let Yc = {
			template : "<h3>粤菜 菜名 : {{$route.query.name}} 价格 : {{$route.query.price}}</h3>"
		}
		
		//2 配置路由 路由可能有多个
		const myRoutes = [
			{
				path : "/home",
				component : Home
			},
			{
				path : "/foods",
				component : Foods,
				children : [
					{
						path : "bjc/:name/:price",
						component : Bjc
					},
					{
						name : "sccRouter",
						path : "scc",
						component : Scc
					},
					{
						path : "xc",
						component : Xc
					},
					{
						path : "yc",
						component : Yc
					}
				]
			},
			{
				path : "*",
				redirect : "/home"
			}
		]
		
		// 3 创建路由对象
		const myRouter = new VueRouter({
			routes : myRoutes,
			mode:'history',
			linkActiveClass : "active"
		});
		
		new Vue({
			router : myRouter //4 注入路由 简写
		}).$mount("#sikiedu");
	</script>
	
</html>

 

五,使用props替代路由对象获取参数

使用路由对象$route获取参数时,组件和路由对象耦合,这里可以使用props来进行解耦;

1,在组件中使用props选项定义数据,接受参数;

2,在路由中,使用props选项来进行设置,路由中的props有三种模式:

  • 布尔模式:props设置为true,可接受params方式的参数传递;
  • 函数模式:props为函数,可接受query方式的参数传递;
  • 对象模式:props为对象。如果处理静态数据,可使用对象模式
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>05_vue-router_passing_props_01</title>
		
		<style type="text/css">
			.active{
				color: #FFFFFF;
				background-color: red;
			}
	    </style>
	</head>
	<body>
		<div id="sikiedu">
			<router-link to="/home">首页</router-link>
			<router-link to="/foods">美食</router-link>
			
			<div>
				<!--将数据显示在这里-->
				<router-view></router-view>
			</div>
		</div>
	</body>
	
	<template id="foods">
		<div>
			<h2>美食广场</h2>
			<ul>
				<router-link to="/foods/bjc/北京烤鸭/68" tag="li">北京菜</router-link>
				<router-link :to="sccParam" tag="li">四川菜</router-link>
				<router-link to="/foods/xc?name=剁椒鱼头&price=128"  tag="li">湘菜</router-link>
				<router-link :to="ycParam"  tag="li">粤菜</router-link>
			</ul>
			
			<router-view></router-view>
		</div>
	</template>
	
	<script type="text/javascript" src="../js/vue.js" ></script>
	<script type="text/javascript" src="../js/vue-router.js" ></script>
	<script>
		
		//1 定义组件
		let Home = {
			template : "<h2>首页</h2>"
		}
		let Foods = {
			template : "#foods",
			data(){
				return {
					sccParam : {
						name : 'sccRouter',
						params : {
							name : '麻婆豆腐',
							price : 28
						}
					},
					ycParam : {
						path : '/foods/yc',
						query : {
							name : '蜜汁叉烧',
							price : 56
						}
					}
				}
			}
		}
		
		//定义foods中的子组件
		let Bjc = {
			props : ['name', 'price'],
			template : "<h3>北京菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Scc = {
			props : ['name', 'price'],
			template : "<h3>四川菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Xc = {
			props : ['name', 'price'],
			template : "<h3>湘菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Yc = {
			props : ['name', 'price'],
			template : "<h3>粤菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		
		//2 配置路由 路由可能有多个
		const myRoutes = [
			{
				path : "/home",
				component : Home
			},
			{
				path : "/foods",
				component : Foods,
				children : [
					{
						path : "bjc/:name/:price",
						component : Bjc,
						props : true
					},
					{
						name : "sccRouter",
						path : "scc",
						component : Scc,
						props : true
					},
					{
						path : "xc",
						component : Xc,
						props : (route) => ({
							name : route.query.name,
							price : route.query.price
						})
					},
					{
						path : "yc",
						component : Yc,
						props : {
							name : '蜜汁叉烧量贩式',
							price : 648
						}
					}
				]
			},
			{
				path : "*",
				redirect : "/home"
			}
		]
		
		// 3 创建路由对象
		const myRouter = new VueRouter({
			routes : myRoutes,
			mode:'history',
			linkActiveClass : "active"
		});
		
		new Vue({
			router : myRouter //4 注入路由 简写
		}).$mount("#sikiedu");
	</script>
	
</html>

 

六,路由的动态跳转

利用vue-router实例方法,使用js对路由进行动态跳转;

  1. router.push:参数为路由对象,跳转到指定路由,跳转后会产生历史记录;
  2. router.replace:参数为路由对象,跳转到指定路由,跳转后不产生历史记录
  3. router.go:参数为numbernumber为正向前跳转,为负向后跳转,根据number的值跳转到对应页面,前提是必须有历史记录可供跳转;
  4. router.back:无参,后退一个页面,需要有历史记录;
  5. router.forward:无参,前进一个页面,需要有历史记录;
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>06_vue-router_dynamic_jump</title>
		
		<style type="text/css">
			.active{
				color: #FFFFFF;
				background-color: red;
			}
		</style>
	</head>
	<body>
		<div id="sikiedu">
			<router-link to="/home">首页</router-link>
			<router-link to="/foods">美食</router-link>
			
			<div>
				<!--将数据显示在这里-->
				<router-view></router-view>
			</div>
			
			<!--动态跳转的按钮-->
			<div>
				<button @click="push">push 返回首页</button><br />
				<button @click="replace">replace 前往美食广场</button><br />
				<button @click="go(-1)">go(-1)</button><br />
				<button @click="go(2)">go(2)</button><br />
				<button @click="back">back 返回1步</button><br />
				<button @click="forward">forward 前进1步</button><br />
			</div>
		</div>
	</body>
	
	<template id="foods">
		<div>
			<h2>美食广场</h2>
			<ul>
				<router-link to="/foods/bjc/北京烤鸭/68" tag="li">北京菜</router-link>
				<router-link :to="sccParam" tag="li">四川菜</router-link>
				<router-link to="/foods/xc?name=剁椒鱼头&price=128"  tag="li">湘菜</router-link>
				<router-link :to="ycParam"  tag="li">粤菜</router-link>
			</ul>
			
			<router-view></router-view>
		</div>
	</template>
	
	<script type="text/javascript" src="../js/vue.js" ></script>
	<script type="text/javascript" src="../js/vue-router.js" ></script>
	<script>
		
		//1 定义组件
		let Home = {
			template : "<h2>首页</h2>"
		}
		let Foods = {
			template : "#foods",
			data(){
				return {
					sccParam : {
						name : 'sccRouter',
						params : {
							name : '麻婆豆腐',
							price : 28
						}
					},
					ycParam : {
						path : '/foods/yc',
						query : {
							name : '蜜汁叉烧',
							price : 56
						}
					}
				}
			}
		}
		
		//定义foods中的子组件
		let Bjc = {
			props : ['name', 'price'],
			template : "<h3>北京菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Scc = {
			props : ['name', 'price'],
			template : "<h3>四川菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Xc = {
			props : ['name', 'price'],
			template : "<h3>湘菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Yc = {
			props : ['name', 'price'],
			template : "<h3>粤菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		
		//2 配置路由 路由可能有多个
		const myRoutes = [
			{
				path : "/home",
				component : Home
			},
			{
				path : "/foods",
				component : Foods,
				children : [
					{
						path : "bjc/:name/:price",
						component : Bjc,
						props : true
					},
					{
						name : "sccRouter",
						path : "scc",
						component : Scc,
						props : true
					},
					{
						path : "xc",
						component : Xc,
						props : (route) => ({
							name : route.query.name,
							price : route.query.price
						})
					},
					{
						path : "yc",
						component : Yc,
						props : {
							name : '蜜汁叉烧量贩式',
							price : 648
						}
					}
				]
			},
			{
				path : "*",
				redirect : "/home"
			}
		]
		
		// 3 创建路由对象
		const myRouter = new VueRouter({
			routes : myRoutes,
			mode:'history',
			linkActiveClass : "active"
		});
		
		new Vue({
			router : myRouter, //4 注入路由 简写
			methods : {
				push(){
					myRouter.push({
						path : '/home'
					});
				},
				replace(){
					myRouter.replace({
						path : '/foods'
					});
				},
				go(n){
					myRouter.go(n);
				},
				back(){
					myRouter.back();
				},
				forward(){
					myRouter.forward();
				}
			}
		}).$mount("#sikiedu");
	</script>
	
</html>

七,路由&过渡

路由可以结合过渡效果使用;

使用<transition></transition><router-view></router-view>包裹住,再写样式即可。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>07_vue-router_transition</title>
		<link rel="stylesheet" href="../css/animate.css" />
		
		<style type="text/css">
			.active{
				color: #FFFFFF;
				background-color: red;
			}
			.sikiedu-router-view{
				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="sikiedu">
			<router-link to="/home">首页</router-link>
			<router-link to="/foods">美食</router-link>
			
			<div class="sikiedu-router-view">
				<!--将数据显示在这里-->
				<transition enter-to-class='animated fadeInLeft delay-1s'
								   leave-to-class='animated fadeOutRight'	
				>
					<router-view></router-view>
				</transition>
			</div>
			
		</div>
	</body>
	
	<template id="foods">
		<div>
			<h2>美食广场</h2>
			<ul>
				<router-link to="/foods/bjc/北京烤鸭/68" tag="li">北京菜</router-link>
				<router-link :to="sccParam" tag="li">四川菜</router-link>
				<router-link to="/foods/xc?name=剁椒鱼头&price=128"  tag="li">湘菜</router-link>
				<router-link :to="ycParam"  tag="li">粤菜</router-link>
			</ul>
			
			<transition enter-to-class='animated fadeInLeft delay-1s'
								   leave-to-class='animated fadeOutRight'>
					<router-view></router-view>
				</transition>
		</div>
	</template>
	
	<script type="text/javascript" src="../js/vue.js" ></script>
	<script type="text/javascript" src="../js/vue-router.js" ></script>
	<script>
		
		//1 定义组件
		let Home = {
			template : "<h2>首页</h2>"
		}
		let Foods = {
			template : "#foods",
			data(){
				return {
					sccParam : {
						name : 'sccRouter',
						params : {
							name : '麻婆豆腐',
							price : 28
						}
					},
					ycParam : {
						path : '/foods/yc',
						query : {
							name : '蜜汁叉烧',
							price : 56
						}
					}
				}
			}
		}
		
		//定义foods中的子组件
		let Bjc = {
			props : ['name', 'price'],
			template : "<h3>北京菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Scc = {
			props : ['name', 'price'],
			template : "<h3>四川菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Xc = {
			props : ['name', 'price'],
			template : "<h3>湘菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		let Yc = {
			props : ['name', 'price'],
			template : "<h3>粤菜 菜名 : {{name}} 价格 : {{price}}</h3>"
		}
		
		//2 配置路由 路由可能有多个
		const myRoutes = [
			{
				path : "/home",
				component : Home
			},
			{
				path : "/foods",
				component : Foods,
				children : [
					{
						path : "bjc/:name/:price",
						component : Bjc,
						props : true
					},
					{
						name : "sccRouter",
						path : "scc",
						component : Scc,
						props : true
					},
					{
						path : "xc",
						component : Xc,
						props : (route) => ({
							name : route.query.name,
							price : route.query.price
						})
					},
					{
						path : "yc",
						component : Yc,
						props : {
							name : '蜜汁叉烧量贩式',
							price : 648
						}
					}
				]
			},
			{
				path : "*",
				redirect : "/home"
			}
		]
		
		// 3 创建路由对象
		const myRouter = new VueRouter({
			routes : myRoutes,
			mode:'history',
			linkActiveClass : "active"
		});
		
		new Vue({
			router : myRouter, //4 注入路由 简写
			methods : {
				push(){
					myRouter.push({
						path : '/home'
					});
				},
				replace(){
					myRouter.replace({
						path : '/foods'
					});
				},
				go(n){
					myRouter.go(n);
				},
				back(){
					myRouter.back();
				},
				forward(){
					myRouter.forward();
				}
			}
		}).$mount("#sikiedu");
	</script>
	
</html>

示例

import Vue from 'vue'
import VueRouter from 'vue-router'
import jwt_decode from "jwt-decode";

import { Message } from 'element-ui';
import { getToken, removeToken } from "@/utils/token-util";


Vue.use(VueRouter)
const WHITE_LIST = ['/login']


const routes = [{
  path: '/',
  name: 'home',
  component: () => import("@/views/home.vue"),
  redirect: "/index",
  children: [{
    path: '/index',
    name: 'index',
    component: () => import("@/views/index"),
  }, {
    path: '/test',
    name: 'test',
    component: () => import("@/views/test"),
  }]
}, {
  path: '/login',
  name: 'login',
  component: () => import("@/views/login"),
},
{
  path: '*',
  component: () => import('@/views/exception/NotFound')
}]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (jwt_decode(getToken()).exp < parseInt(new Date().getTime() / 1000)) {
      // 已过期
      Message.warning("登录状态已过期, 请重新登录")
      localStorage.clear();

      next({
        path: '/login',
        query: to.path === '/' ? {} : { from: to.path }
      });
    } else {
      next();
    }
  }
  else if (WHITE_LIST.includes(to.path)) {
    next();
  }
  else {

    next({
      path: '/login',
      query: to.path === '/' ? {} : { from: to.path }
    });
  }
});

export default router

登录后,跳转方式:

    /* 跳转到首页 */
    goHome() {
      this.$router.push(this.$route?.query?.from ?? "/").catch(() => {});
    },

Logo

前往低代码交流专区

更多推荐