06-路由配置

路有基础

概念

前端路由主要根据不同的事件,显示不同的页面内容,本质上是用户事件与事件处理函数之间的对应关系;
后台路由则是根据不同的URL请求,返回不同的服务器资源;
Vue专用的路由工具库VueRouter,叫做路由管理器。

  • route
    • 单数
    • 路由
    • 理解为单个路由或者某一个路由
  • routes
    • 复数
    • 多个路由的集合
    • 官方定义也是表示多个数组的集合
  • router
    • 路由器
    • 包含route和routes的容器
    • 管理者,负责从routes中查找route
    • 功能:
      • 嵌套的路由/视图表
      • 模块化的、基于组件的路由配置
      • 路由参数、查询、通配符
      • 基于vue.js过度系统的视图过度效果
      • 细粒度的导航控制
      • 自定义的滚动条行为

安装

  • 创建项目时候,选择上
  • 通过命令进行安装
    • npm i vue-router@next
    • 需要通过Vue.use()方法将其纳入到实例中

使用

  • 使用createRouter方法创建一个路由器router
  • 指定内容:
    • 使用什么方法使用路由(两种方法:history模式和hash模式)
      • history模式:createWebHistory(process.env.BASE_URL)
      • hash模式:createWebHashHistory()
    • 路由数组
      • 每一个对象都是一个路由对象
      • 三部分
        • name:链接名称
        • path:当前路由规则匹配的hash地址
        • component:当前路由规则对应要展示的组件
import {createRouter, createWebHashHistory} from 'vue-router'
import HelloWorld from '../views/HelloWorld.vue'

const routes = [
	// 指定默认路由
	{
		path: '/',
		name: 'HelloWorld',
		component: HelloWorld
	},
	{
		path: '/login',
		name: 'login',
		component: () => impport('../views/Login.vue')
	}
]

// 创建管理器
const router = createRouter({
	// 指定history模式
	history: createWebHistory(process.env.BASE_URL),
	routers
})
export default router

路由重定向

使用的是路由管理规则的redirect属性来实现的。

import {createRouter, createWebHashHistory} from 'vue-router'
import HelloWorld from '../views/HelloWorld.vue'

const routes = [
	// 指定默认路由
	{
		path: '/',
		redirect: '/hello'
	},
	{
		path: '/hello',
		name: 'HelloWorld',
		component: HelloWorld
	}
]

// 创建管理器
const router = createRouter({
	// 指定history模式
	history: createWebHistory(process.env.BASE_URL),
	routers
})
export default router

路由链接

<router-link>默认会被渲染为<a>标签,to属性可以用来指定目标地址,会被渲染为href属性

<router-link to="home">home</router-link>
<!-- 其他写法 -->
<router-link :to="home">home</router-link>
<router-link v-bind:to="home">home</router-link>
<router-link :to="{path: 'home'}">home</router-link>
<!-- 命名路由需要在router/index.js中声明name对应的路由 -->
<router-link :to="{name: 'applename'}">to apple</router-link>
<!-- 带有参数的路由,如果是query,name和path都可以使用,并且会被解析为/apple?color=red -->
<router-link :to="{path: 'apple', query: {color: 'red'}}">apple</router-link>
<!-- 只有是name 的时候,params才会生效,且会被解析为/app/red -->
<router-link :to="{name: 'apple', params: {color: 'red'}}">apple</router-link>

添加一些激活样式可以通过actrive-class属性来实现

路由占位符

用来将通过路由规则匹配到的组件渲染到组件占位符的位置上

<router-view></router-view>

编程式导航

导航有两种方式:

  • 声明式导航
    • 通过单击定义的链接实现导航的方式
  • 编程式导航
    • 通过调用js形式的API来实现导航的形式
    • 基本方法
      • router.push()方法
        • 可以导航到不同的URL中
        • 原理:向history中添加一个新的记录,当用户单击“后退”按钮,会回退到上一次访问的浏览器网页
        • 单击<router-link to=''>方法等同于调用该方法
      • router.replace()方法
        • 类似push方法,区别是不想浏览器的history中添加新的记录而是替换当前的history记录
      • router.go()方法
        • 参数是一个整数,代表前进或者后退多少步
        • 如果history记录不够用,将导航失败
// router.push方法
router.push('home')
router.push({path: 'home'})
router.push({name: 'user', params: {userId: '123'}})
// /register?plan=private
router.push({path: 'home', query: {plan: 'private'}})
router.push({path: `/user/${userId}`})

// router.go
// 前进
router.go(1);
// 后退
router.go(-1);

实现方法

// 1.引入useRouter方法
import {userRouter} from 'vue-router'
// 2.使用和操作,示例如下
const router = useRouter()
const homeClick = () => {
	router.push('about');
}

动态路由

静态路由

单个页面实现多个路径信息,比如/user/lb/user/wq
实现思路:

<router-link to="/user/lb"></router-link>
<router-link to="/user/wq"></router-link>

<!-- 定义路由规则 -->
const routers = [
	{path: '/user/lb', component: User},
	{path: '/user/wq', component: User}
]

使用vue-router进行穿传递参数的路由称之为静态路由

动态路由

<!-- 动态路径参数 -->
const routers = [
	{path: '/user/:userId', component: User}
]
<!-- 在路由组件中通过下面的语句获取参数 -->
route.params.userId

嵌套路由

步骤:

  • 1.创建对应的子组件,并在路由映射中配置对应的子路由
  • 2.在父组件中通过使用<router-view>标签
import {createRouter, createWebHashHistory} from 'vue-router'
import Home from '../views/Home.vue'
const HomeNews = () => import('../components/HomeNews.vue')
const HomeMsg = () => import('../components/HomeMsg.vue')
const routes = [
	{
		path: '/home',
		name: 'Home',
		component: Home,
		// 子路由
		children: [
			// 默认子路由
			{
				path: '',
				component: HomeNews
			},
			{
				path: 'news',
				component: HomeNews
			},
			{
				path: 'msg',
				component: HomeMsg
			},
		]
	}
]
const router = createRouter({
	history: createWebHashHistory(),
	routes
})
export default router

路由传递参数

使用router-link标签传递参数

<!-- 使用标签传递参数,通过route.query.参数名进行获取,route对象必须是通过useRoute()方法进行创建的 -->
<router-link :to="{path: '/profile', query: {name: '刘兵', age: 15}}"></router-link>

使用事件方法传递路由参数

使用事件来触发实现路由参数传递

const profileCheck = () => {
	router.push({
		path: '/profile',
		query: {
			name: 'zs',
			age: 12
		}
	});
}

全局导航守卫

主要用来监听路由的进入和离开,然后通过vue-router提供的beforeEach和afterEach的生命周期函数分别在路由即将改变前和改变后触发。

全局前置守卫

router.beforeEach()注册一个全局的前置守卫

const router = new VueRouter({...})
router.beforeEach((to, from, next) => {})

一个导航触发时,全局前置守卫按照顺序进行调用。守卫是异步执行的,此时导航的所有守卫解析完成之前一直处于等待中。
参数介绍:

  • to:目标路由对象
  • from:正要离开的路由
  • next:一定要调用该方法来解析这个生命周期函数
    • next():执行下一个生命周期函数
    • next(false):中断当前的导航。如果浏览器URL改变,那么重置到from路由对应的地址
    • next(‘/’)或者next({path: ‘/’}):跳转到一个不同的地址。

router.afterEach()使用方法同上。

路由元信息

定义路由的时候可以配置meta字段

const routes = [
	// 指定默认路由
	{
		path: '/',
		component: Hello,
		// meta域
		meta: {
			// 属性:属性值
			requiresAuth: true
		}
	}
]

一个路由匹配到的所有路由记录都会暴露为route对象的route.matched数组。可以通过语句to.meta.属性实现检查路由记录中的meta字段。

路由懒加载

正常打包,webpack会将所有用到的组件全部打包到一个文件中,这样文件会很大,且解析的时候加载时间会变长,所以可以采用懒加载。

const 组件名 = () => import('组件名称');

也可以指定webpackChunkName,将多个组件合并打包成一个JavaScript文件

const Home = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/home')
const Index = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/index')

案例:

import {createRouter, createWebHashHistory} from 'vue-router'
import Home from '../views/Home.vue'
import Profile from '../components/Profile.vue'
const HomeNews = () => import('../components/HomeNews.vue')
const HomeMsg = () => import('../components/HomeMsg.vue')
const routes = [
	{
		path: '/',
		redirect: '/home'
	},
	{
		path: '/profile/',
		component: Profile,
		meta: {
			title: '简介'
		}
	}
	{
		path: '/home',
		name: 'Home',
		component: Home,
		meta: {
			title: '主页'
		}
		// 子路由
		children: [
			// 默认子路由
			{
				path: '',
				component: HomeNews
			},
			{
				path: 'news',
				component: HomeNews
			},
			{
				path: 'msg',
				component: HomeMsg
			},
		]
	}
]
const router = createRouter({
	history: createWebHashHistory(),
	routes
})

router.beforeEach((to, from, next) => {
	if(to.matched[0].name ==== 'User'){
		console.log('拦截')
	}else{
		//读取路由元信息,并修改网页标题
		document.title = to.meta.title
		// 跳转到指定页面
		next()
	}
});
export default router

新增路由

使用方法:

  • 增加单挑路由router.addRoute({})
  • 增加指定父路由的子路由rouiter.addRoute('父路由名', {})
import {createRouter, createWebHashHistory} from 'vue-router'
const router = createRouter({
	history: createWebHashHistory(),
	routes
})

router.addRoute({
	path: 'msg',
	name: 'Msg',
	component: () => import('../components/Msg.vue')
})
router.addRoute('Msg', {
	path: '/msg/info',
	component: () => import('../components/Info.vue')
})
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值