Vue 路由允许我们通过不同的 URL 访问不同的内容。通过 Vue 可以实现多视图的单页Web应用
一、入门(安装及配置)
1. 安装vue-router
npm i vue-router --save
2. 配置vue-router
新建 router
文件夹
路径:/src/router
路径:/src/router/index.js
index.js
import {createRouter,createWebHistory } from 'vue-router'
const routes = [
{
path:'/',
component:() => import('../pags/login.vue')
}
]
const router = createRouter({
history:createWebHistory(),
routes //路由信息
})
export default router
main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
App.js
<template>
<router-view/>
</template>
<script>
export default {
}
</script>
<style>
</style>
第二章 命名路由-编程式导航(跳转)
除了 path
之外,你还可以为任何路由提供 name
。这有以下优点:
- 没有硬编码的 URL
params
的自动编码/解码。- 防止你在 url 中出现打字错误。
- 绕过路径排序(如显示一个)
const routes:Array<RouteRecordRaw> = [
{
path:"/",
name:"Login",
component:()=> import('../components/login.vue')
},
{
path:"/reg",
name:"Reg",
component:()=> import('../components/reg.vue')
}
]
router-link跳转方式需要改变 变为对象并且有对应name
<h1>小满最骚</h1>
<div>
<router-link :to="{name:'Login'}">Login</router-link>
<router-link style="margin-left:10px" :to="{name:'Reg'}">Reg</router-link>
</div>
<hr />
编程式导航
除了使用 <router-link>
创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。
1.字符串模式
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = () => {
router.push('/reg')
}
2.对象模式
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = () => {
router.push({
path: '/reg'
})
}
3.命名式路由模式
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = () => {
router.push({
name: 'Reg'
})
}
a标签跳转
直接通过a href也可以跳转但是会刷新页面
<a href="/reg">rrr</a>
参考:小满Router(第二章-命名路由-编程式导航)_小满zs的博客-优快云博客
第三章 历史记录
replace的使用
采用replace进行页面的跳转会同样也会创建渲染新的Vue组件,但是在history中其不会重复保存记录,而是替换原有的vue组件;
该方法的原理是: 替代
router.replace 跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
router-link 使用方法
<router-link replace to="/">Login</router-link>
<router-link replace style="margin-left:10px" to="/reg">Reg</router-link>
编程式导航
<button @click="toPage('/')">Login</button>
<button @click="toPage('/reg')">Reg</button>
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = (url: string) => {
router.replace(url)
}
横跨历史
该方法采用一个整数作为参数,表示在历史堆栈中前进或后退多少步
<button @click="next">前进</button>
<button @click="prev">后退</button>
const next = () => {
//前进 数量不限于1
router.go(1);
}
const prev = () => {
//后退
//router.go(-1);
router.back();
}
参考小满Router(第三章-历史记录)_小满zs的博客-优快云博客_router 历史记录
第四章 路由传参
useRouter与useRoute的区别
useRouter是全局对象,用来传入参数。useRoute是当前对象,用来接收参数
useRouter介绍及使用
1. router是VueRouter的一个对象,通过Vue.use(VueRouter)和VueRouter构造函数得到一个router的实例对象,这个对象中是一个全局的对象,包含了所有的路由包含了许多关键的对象和属性。例如history对象
- $router.push({path:’/path’}); 本质是向history栈中添加一个路由,在我们看来是 切换路由,但本质是在添加一个history记录
- $router.replace({path:’/path’}); 替换路由,没有历史记录
useRoute介绍及使用
2. route是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象,可以获取对应的name,path,params,query等
- $route.path
- 字符串,等于当前路由对象的路径,会被解析为绝对路径,如 “/index/” 。
- $route.params
- 对象,包含路由中的动态片段和全匹配片段的键值对
- $route.query
- 对象,包含路由中查询参数的键值对。例如,对于 /index?id=1 ,会得到 $route.query.id == 1。
params传参合query传参的区别
1. params参数在地址栏中不会显示,query会显示
this.router.push({path:'/customList',params:{id:6}}) this.router.push({path:'/customList',query:{id:6}})
params: http://localhost:8080/#/customList
query:http://localhost:8080/#/customList?id=62.网页刷新后params参数会不存在
Params路由传参
编程式导航 使用router.push 或者 replace 的时候 改为对象形式并且只能使用name,path无效,然后传入params
使用useRouter传入参数(params)
语法:
router.push({ name:'listSecond', params:{ id, tips}})
<template>
<div>
<div class="list-style"
v-for="item in listItem"
:key="item.id"
@click="handlerId(item?.id,item?.tips)"
>{{item.title}}</div>
</div>
</template>
<script>
import {defineComponent, ref} from 'vue'
import {useRouter} from 'vue-router'
export default defineComponent({
setup() {
const listItem = ref([
{
title:'标题一',
id:1,
tips:'title-one'
},
{
title:'标题二',
id:2,
tips:'title-second'
}
])
const router = useRouter();
const handlerId =(id,tips) =>{
//params的属性值只能为 对象
router.push({name:'listSecond',params:{id,tips}})
}
return{listItem,handlerId}
}
})
</script>
使用useRoute接收参数(params)
import { useRoute } from 'vue-router';
const route = useRoute()
<div>ID:{{ route.params?.id }}</div>
动态路由传参
很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数 。
路径参数 用冒号 : 表示。当一个路由被匹配时,它的 params 的值将在每个组件
因为用params路由传参,刷新界面会失去参数。配置动态路由之后就刷新后依然存在。
{
path:'/listFirst',
name:'listFirst',
component:()=>import('../pages/transmitInfo/list-first')
},
{
path:'/listSecond/:id/:tips',//配置动态路由参数 :id、:tips
name:'listSecond',
component:()=>import('../pages/transmitInfo/list-second'),
}
Query路由传参
编程式导航 使用router push 或者 replace 的时候 改为对象形式新增query 必须传入一个对象
语法:
router.push({ path:'/listSecond',query:{id,tips}})
使用useRouter传入参数(params)
const router = useRouter();
const handlerId =(id,tips) =>{
router.push({path:'/listSecond',query:{id,tips}})
}
使用useRoute接收参数(params)
import { useRoute } from 'vue-router';
const route = useRoute()
<div>ID:{{ route.query?.id }}</div>
import { useRoute } from 'vue-router';
import { data } from './list.json'
const route = useRoute()
const item = data.find(v => v.id === Number(route.params.id))
二者的区别
- query 传参配置的是 path,而 params 传参配置的是name,在 params中配置 path 无效
- query 在路由配置不需要设置动态路由参数,而 params 必须设置
- query 传递的参数会显示在地址栏中
- params传参刷新会无效(设置动态路由参数后有效),但是 query 会保存传递过来的值,刷新不变 ;
- 路由配置
第五章 嵌套路由
一些应用程序的 UI 由多层嵌套的组件组成。在这种情况下,URL 的片段通常对应于特定的嵌套组件结构,例如:导航栏右侧显示 另一页面(父子路由)
const routes: Array<RouteRecordRaw> = [
{
path:'/search',
component:search,
redirect:'/search/htmlcontent',
children:[
{
// 子路由的path里面的值不需要加 /
path:'htmlcontent',
component:()=>import('../components/serch/htmlcontent')
},
{
path:'csscontent',
component:()=>import('../components/serch/csscontent')
}
]
}
]
如你所见,children
配置只是另一个路由数组,就像 routes
本身一样。因此,你可以根据自己的需要,不断地嵌套视图。children里面的path属性值不要加 /
TIPS:不要忘记写router-view
router-view 当你的路由path 与访问的地址相符时,会将指定的组件替换该 router-view
<div>
<router-view></router-view>
<div>
//不要忘记 需要写上父路由
<router-link to="/search">login</router-link>
<router-link style="margin-left:10px;" to="/search/htmlcontent">htmlcontent</router-link>
</div>
</div>
方式二 使用 ruoter.push
<template>
<div>
<div class="search-style">
<div class="nav-left">
<div class="navitem-style" v-for="item in navlist" :key="item.id" @click="handerNav(item.path)">{{item.title}}</div>
</div>
<div class="nav-content">
<router-view></router-view>
</div>
</div>
</div>
</template>
<script>
import {defineComponent,ref} from 'vue'
import {useRouter} from 'vue-router'
export default defineComponent({
setup(){
const route = useRouter();
const navlist = ref([
{
title:'HTML',
id:1,
path:'/htmlcontent'
},
{
title:'CSS',
id:2,
path:'/csscontent'
}
])
const handerNav =(path)=>{
route.push('/search'+path);
}
return{navlist,handerNav}
}
})
</script>
参考 小满Router(第六章-命名视图)_小满zs的博客-优快云博客
第六章 命名视图(同一级(组件)中展示更多的路由视图)
命名视图可以在同一级(同一个组件)中展示更多的路由视图,而不是嵌套显示。 命名视图可以让一个组件中具有多个路由渲染出口,这对于一些特定的布局组件非常有用。 命名视图的概念非常类似于“具名插槽”,并且视图的默认名称也是 default。
一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 components 配置 (带上 s)
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path:'/listFirst',
name:'listFirst',
component:()=>import('../pages/transmitInfo/list-first'),
children:[
{
path:'listFirstA',
components:{
default:()=>import('../components/listFirstA')
}
},
{
path:'listFirstB',
components:{
listFirstB1:()=>import('../components/listFirstB1'),
listFirstB2:()=>import('../components/listFirstB2')
}
}
]
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
对应Router-view 通过name 对应组件
<div>
<div>
<router-link to='/listFirst/listFirstA'>goodsCount</router-link>
<router-link
style="margin-left:20px;"
to='/listFirst/listFirstB'>
listFirstB</router-link>
<hr>
<div>
<router-view></router-view>
<router-view name='listFirstB1'></router-view>
<router-view name='listFirstB12'></router-view>
</div>
</div>
</div>
参考小满Router(第六章-命名视图)_小满zs的博客-优快云博客
第七章 重定向&别名
重定向 redirect
1.字符串形式配置,访问/ 重定向到 /user (地址栏显示/,内容为/user路由的内容)
const routes: Array<RouteRecordRaw> = [
{
path:'/',
component:()=> import('../components/root.vue'),
redirect:'/user1',
children:[
{
path:'/user1',
components:{
default:()=> import('../components/A.vue')
}
},
{
path:'/user2',
components:{
bbb:()=> import('../components/B.vue'),
ccc:()=> import('../components/C.vue')
}
}
]
}
]
2.对象形式配置
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component: () => import('../components/root.vue'),
redirect: { path: '/user1' },
children: [
{
path: '/user1',
components: {
default: () => import('../components/A.vue')
}
},
{
path: '/user2',
components: {
bbb: () => import('../components/B.vue'),
ccc: () => import('../components/C.vue')
}
}
]
}
]
3.函数模式(可以传参)
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component: () => import('../components/root.vue'),
redirect: (to) => {
return {
path: '/user1',
query: {
id:1
}
}
},
children: [
{
path: '/user1',
components: {
default: () => import('../components/A.vue')
}
},
{
path: '/user2',
components: {
bbb: () => import('../components/B.vue'),
ccc: () => import('../components/C.vue')
}
}
]
}
]
别名 alias
将 path的属性值 '/
'别名为 '/
root','/
root2','/
root3',意味着当用户访问 /
root , /
root2 , /
root3'时,URL是 /
root 或 /
root2 或 /
root3
,但会被匹配为用户正在访问 /
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component: () => import('../components/root.vue'),
alias:["/root","/root2","/root3"],
children: [
{
path: 'user1',
components: {
default: () => import('../components/A.vue')
}
},
{
path: 'user2',
components: {
bbb: () => import('../components/B.vue'),
ccc: () => import('../components/C.vue')
}
}
]
}
]