路由就是一组key-value的对应关系。
多个路由,需要经过路由器的管理。
首先yarn安装路由:
yarn add vue-router
ts:创建一个路由器,并暴露出去
第一步,引入ceateRouter
import { createRouter,createWebHistory } from "vue-router";
import Home from "@/components/Home.vue";
import News from "@/components/News.vue";
import About from "@/components/About.vue";
第二步,创建路由器
const router = createRouter({
history: createWebHistory(),//路由器工作模式
routes:[
{
name:'shouye'//路由命名
path:'/home',
component: Home
},
{
path:'/news',
component: News
},
{
path:'/about',
component: About
}
]
})
第三步,暴露出去
export default router
vue:展示到页面上
<RouterView></RouterView>
实现路由的切换,active-class被激活的时候展示:
<RouterLink to="/home" active-class="active">首页</RouterLink>
<RouterLink to="/news" active-class="active">新闻</RouterLink>
<RouterLink to="/about" active-class="active">关于</RouterLink>
注意:路由组件通常存放在pages或views文件夹,一般组件通常存放在components文件夹,通过点击导航栏,视觉效果上“消失”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
to的两种写法:
<router-link active-class="active" :to="{ path: '/home' }">首页</router-link>
<RouterLink to="/home" active-class="active">首页</RouterLink>
<router-link active-class="active" :to="{ name: 'shouye' }">首页</router-link>
两种写法是等价的,另外router-link和RouterLink写法也是等价的
路由器工作模式:
1、history模式:
优点是URL更加美观,不带有#,更接近传统的网站URL,缺点是后期项目上线,需要服务器配合处理路径问题,否则刷新会有404错误。
vue2:mode:'history'
vue3:history:createWebHistory()
React: BrowserRouter
2、hash模式:
优点是兼容性好,因为不需要服务器处理路径,确定是URL带有#不太美观,且在SEO优化方面相对较差。
vue3:history: createWebHashHistory()
路由嵌套:
{
path: '/news',
component: News,
children:[
{
path:'detail',
component:Detail
}
]
}
query参数:
1、拼参数
<router-link :to="`/news/detail?id=${news.id}&title=${news.title}&content=${news.content}`">{{ news.title }}</router-link>
2、对象形式
<router-link :to="{
path: '/news/detail',
query:
{
id: news.id,
title: news.title,
content: news.content
}
}">{{ news.title }}</router-link>
params参数(坑多,不推荐):
创建路由的时候做好占位:
{
path: '/news',
component: News,
children:[
{
name:'xiangqing',
path:'detail/:id/:title/:content',
component:Detail
}
]
}
第一种直接/拼接即可
<router-link :to="`/news/detail/${news.id}/${news.title}/${news.content}`">{{ news.title }}</router-link>
第二种不能用path,只能用name
路由的props三种写法:
第一种写法,将路由收到的所有params参数作为props传给路由组件
props: true
defineProps(['id','title','content'])
第二种函数写法,query可以返回一个对象
props(route) {
return route.query
}
同样
defineProps(['id','title','content'])
第三种,对象写法,可以直接返回一个对象给路由
props:{
id:'001'
title:"",
content:""
}
replace属性
默认是push属性,是有历史记录的,设置为replace属性后不保存历史记录
<RouterLink replace to="/news" active-class="active">新闻</RouterLink>
编程式路由导航
脱离RouterLink实现路由跳转,进入首页后,3秒跳转某个路由
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()
onMounted(()=> {
setTimeout(() => {
router.push('/news')
}, 3000);
})
push()内写法和to多种写法一致
重定向
在进入页面后,会自动定位到首页
在routes最后写入
{
path: '/',
redirect: '/home'
}










网友评论