路由
- 理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
- 前端路由:key是路径,value是组件。
- 路由标签
<router-link></router-link>
限于<a href>
转换使用,若使用在其他标签会破坏代码结构
简单应用
- 安装vue-router,命令:
npm i vue-router
- 应用插件:
Vue.use(VueRouter)
- 编写router配置项:
//创建路由器
import VueRouter from "vue-router";
//配置路由组件
import About from "../pages/About";
import Home from "../pages/Hone"
//创建router实例对象,去管理一组一组的路由规则,并导出创建好的路由
export default new VueRouter({
routes: [
{
path: "/about",//路由名称
component: About//配置路由组件
},
{
path: "/home",
component: Home
}
]
})
1.指定展示位置
<router-view></router-view>
2.实现切换(active-class可配置高亮样式)、
<router-link active-class="active" to="/about">About</router-link>
路由几个注意点
一、注意分类文件夹:
- 有路由组件的配置在一个文件夹中,通常存放在pages文件夹 。
- 一般组件通常存放在components文件夹
- 每个组件都有自己的
$route
属性,里面存储着自己的路由信息。 - 整个应用只有一个router,可以通过组件的
$router
属性获取到。
多级路由
配置路由规则,使用children配置项:
routes:[
{
path:'/about',
component:About,
},
{
path:'/home',
component:Home,
children:[ //通过children配置子级路由
{
path:'news', //此处一定不要写:/news
component:News
},
{
path:'message',//此处一定不要写:/message
component:Message
}
]
}
]
2.跳转(要写完整路径):
<router-link to="/home/news">News</router-link>
路由的query参数
<!-- 跳转并携带query参数,to的字符串写法 -->
<router-link
:to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{
m.title
}}
</router-link>
<!-- 跳转并携带query参数,to的对象写法 -->
<router-link
:to="{
path:'/home/message/detail',
query:{
id: m.id,
title: m.title,
}
}"
>跳转</router-link>
路由组件 接收参数:
$route.query.id
$route.query.title