【JavaWeb学习】路由 vue-router

1. 简介

vue-router 是 vue 里的一个插件库,专门用来实现SPA应用。
SPA应用是单页Web应用(Single Page Web Application),整个应用只有一个完整的页面;点击页面中的导航连接不会刷新页面,只会做页面的局部更新,其数据需要通过 ajax 请求获取;
一个路由就是一组 key - value 对应关系,key为路径,value可能是functioncomponent;多个路由需要经过路由器的管理;

前端路由
valuecomponent,用于展示页面内容;
当浏览器的页面改变时,显示对应的组件。
后端路由
valuefunction,用于处理客户端提交的请求;
服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据。

2. 基本使用

  • 安装npm i vue-router@3(Vue2)或npm i vue-router(Vue3)
  • 应用插件Vue.use(VueRouter)
  • 编写 router 配置项
   //引入VueRouter
   import VueRouter from 'vue-router'
   //引入Luyou 组件
   import About from '../components/About'
   import Home from '../components/Home'
   
   //创建router实例对象,去管理一组一组的路由规则
   const router = new VueRouter({
   	routes:[
   		{
   			path:'/about',
   			component:About
   		},
   		{
   			path:'/home',
   			component:Home
   		}
   	]
   })
   
   //暴露router
   export default router
  • 实现切换(active-class可以配置高亮样式)
<router-link active-class="active" to="/about">About</router-link>
  • 指定展示位置<router-view></router-view>
注意
  • 路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。
  • 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
  • 每个组件都有自己的$route属性,里面存储着自己的路由信息。
  • 整个应用只有一个router,可以通过组件的$router属性获取到。

3. 嵌套(多级)路由

  • 配置路由规则,使用children配置项
export default new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home,
			children:[
				{
					path:'news',  // 此处不能像一级路由一样加'/'
					component:News
				},
				{
					path:'message',  // 此处不能像一级路由一样加'/'
					component:Message
				}
			]
		}
	]
})
  • 跳转,要写完整路径
<router-link to='/home/message'>Message</router-link>

4. query参数

  • 传递参数
<!-- 跳转路由并携带query参数,to的字符串写法 -->
<router-link :to="/home/message/detail?id=007&title=hello">{{m.title}}</router-link>
<!-- 跳转路由并携带query参数,to的对象写法 -->
<router-link :to="{
	path:'/home/message/detail',
	query:{
		id:007,
		title:hello
	}
}">
	{{m.title}}
</router-link>
  • 接收参数
$route.query.id
$route.query.title

5. 命名路由

  • 作用:简化路由的跳转
  • 使用
export default new VueRouter({
	routes:[
		{
			name:'firstleval_about', // 给路由命名
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home,
			children:[
				{
					path:'news',
					component:News
				},
				{
					path:'message',
					component:Message,
					children:[
						{
							name:'thridleval_message', // 给路由命名
							path:'detail',
							component:Detail,
						}
					]
				}
			]
		}
	]
})
<router-link class="list-group-item" active-class="active" :to="{name:'firstleval_about'}">About</router-link>
<!-- 命名路由: 在index.js里给路由设置一个name配置项,然后把 path:'/home/message/detail' 换成 name:'thridleval_message' -->
<router-link :to="{
	name:'thridleval_message',
	query:{
		id:m.id,
		title:m.title
	}
}">
	{{m.title}}
</router-link>

5. params参数

  • 配置路由,声明接收 params 参数
export default new VueRouter({
	routes:[
		{
			name:'firstleval_about',
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home,
			children:[
				{
					path:'news',
					component:News
				},
				{
					path:'message',
					component:Message,
					children:[
						{
							name:'thridleval_message',
							path:'detail/:id/:title', // 使用占位符声明接收 params 参数
							component:Detail,
						}
					]
				}
			]
		}
	]
})
  • 传递参数
    如果使用 to 的对象写法,那么必须用 name 配置不能用 path配置
<router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>
<!-- params参数: 在index.js里给路由路径加上占位符,然后把 query 改成 params; 使用 params 时必须用 name, 不能用 path -->
<router-link :to="{
	name:'thridleval_message',
	params:{
		id:m.id,
		title:m.title
	}
}">
	{{m.title}}
</router-link>	
  • 接收参数
$route.params.id
$route.params.title

如何指定params参数可传可不传?
如果路由要求传递params参数,但我们不想传递,那么会发现 url 出现问题。可以在配置路由路径中,params参数的占位符后加一个?,代表该参数可传可不传,如 path:'detail/:id/:title?'
params参数可传可不传时,如果传递的是空串,如何解决?
使用undefined解决,params:{keyword: '' || undefined}

6. props配置

让组件更方便地收到参数。

{
	name:'thridleval_message',
	path:'detail', 
	// path:'detail/:id/:title', // 使用占位符声明接收 params 参数
	component:Detail,
	// props 的第一种写法:值为对象:该对象中的所有 key-value都会以props的形式传给 Detail 组件
	props:{a:1, b:'hello'}
	// props 的第二种写法:值为 bool 值:若布尔值为真,则会把该路由组件收到的所有 params参数以 props 的形式传给 Detail 组件
	props:true
	// props 的第三种写法:值为函数:该函数返回的对象中每一组 key-value 都会通过 props 传给 Detail 组件
	props($route){
		return {id:$route.query.id, title:$route.query.title}
	}
}

7. router-link的 replace 属性

  • 作用:控制路由跳转时操作浏览器历史记录的模式
  • 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
  • 如何开启replace模式:<router-link replace .......>News</router-link>

8. 编程式路由导航

  • 作用:不借助<router-link> 实现路由跳转,让路由跳转更加灵活
  • 具体编码:
//$router的两个API
this.$router.push({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx
		}
})

this.$router.replace({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx
		}
})
this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //可前进也可后退

9. 缓存路由组件

让不展示的路由组件保持挂载,不被销毁。

<keep-alive include="组件名">
	<router-view></router-view>
</keep-alive>
// 有多个组件需要缓存时,可以写成数组
<keep-alive :include=["News", "Message"]>

10. 两个新的生命周期钩子

路由组件独有的两个钩子,用于捕获路由组件的激活状态。
路由组件被激活时触发activated(){}
路由组件失活时触发deactivated(){}

11. 路由守卫

对路由进行权限控制。
路由配置中加入 meta 项,里面存放自己的设置。

{
	name:'first_about',
	path:'/about',
	component:About,
	meta:{ title: '关于'}
}

11.1. 全局前置路由守卫

初始化和每一次路由切换之前执行。

router.beforeEach((to, from, next)=>{
	// console.log('前置路由守卫', to, from);
	if(to.meta.isAuth){ // 判断是否需要鉴定权限
		if(localStorage.getItem('school')==='empire'){ // 权限控制的具体规则
			next();
		}else{
			alert('你的学校无权限访问嗷.');
		}
	}else{
		next(); // 放行
	}	
}); 

11.2. 全局后置路由守卫

初始化和每一次路由切换之后执行。

router.afterEach((to, from)=>{
	console.log('后置路由守卫', to, from);
	document.title = to.meta.title || 'kirlant'; // 修改网页的 title
}); 

11.3. 独享路由守卫

只为某一个路由服务的守卫,只有前置守卫 beforeEnter,要写在路由配置项中。

{
	name:'sec_news',
	path:'news',
	component:News,
	meta:{
		isAuth:true,
		title:'新闻'
	},
	beforeEnter:(to, from, next) => {
		if(to.meta.isAuth){ // 判断是否需要鉴定权限
			if(localStorage.getItem('school')==='empire'){
				next();
			}else{
				alert('你的学校无权限访问嗷.');
			}
		}else{
			next();
		}
	}
}

11.4. 组件内路由守卫

在组件中配置,包括进入守卫和离开守卫。

export default {
		// eslint-disable-next-line vue/multi-word-component-names
		name:'About',
		// 进入守卫:通过路由规则进入该组件时被调用
		beforeRouteEnter(to, from, next){
			console.log('beforeRouteEnter', from);
			if(to.meta.isAuth){ // 判断是否需要鉴定权限
				if(localStorage.getItem('school')==='empire'){
					next();
				}else{
					alert('你的学校无权限访问嗷.');
				}
			}else{
				next();
			}
		},
		// 离开守卫:通过路由规则离开该组件时被调用
		beforeRouteLeave(to, from, next){
			console.log('beforeRouteLeave', to, from);
			next();
		}
	}

11.5. 路由器的history模式与hash模式

对于一个url来说,#及其后面的内容就是**hash值**。
hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器

  • hash模式(默认)
    地址中永远带着#号,不美观 ;
    若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法;
    兼容性较好;
  • history模式
    地址干净,美观 ;
    兼容性和hash模式相比略差;
    应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题:

搭建服务器时,npm i connect-history-api-fallback安装中间件 --> 在server.js 中引入const history = require('connect-history-api-fallback');并应用const app = express(); app.use(history());中间件(注意:要在静态资源use前进行应用)。

在创建路由器时可以通过mode配置项进行设置。

12. Element UI组件库

Element UI
PC端,基于Vue

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值