什么是路由
一个路由就是一组映射关系(key---value)
key为路径,value可能是function或Component
路由的分类
后端路由
服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据
前端路由
当浏览器的路径改变时,对应的组件就会显示
3. 路由的安装
使用vue-cli进行安装,vue2对应的版本为vue-router@3,使用npm i vue-router@3进行安装
1.跳转到项目根目录下

2. 使用npm i vue-router@3安装

4. 配置路由
在src下创建router文件夹,该文件夹下创建index.js文件,具体内容如下
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
//引入对应的路由组件
import xxx from 'xxx'
//创建并暴露一个router
export default new VueRouter({
routes:[
{
path:'/跳转路径',
component:xxx
},
]
})
在main.js文件中配置router
import router from './router'
//应用
Vue.use(router)
//创建vm
new Vue({
el:'#app',
router,
render: h => h(App),
})
在App.vue页面中添加<router-view>标签
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
5. 使用路由
router-link标签可以设置to属性
<div id='app'>
<router-link to="/index">index </router-link>
<router-link to="/detail">去详情 </router-link>
<div>
函数式跳转this.$router.push(path)
//query传参的
this.$router.push({path:'/detail',query:{id:103}})
//通过 this.$router.query.id 接收参数
//params传参的
this.$router.push({
name:"my",
params:{userid:999}
})
//通过 this.$router.params.userid 接收参数
重定向跳转
//在router文件夹下的index.js文件中
{
//跳转路径
path:'/',
//重定向路径
redirect:'/login'
},
6. 子路由的设置
声明路由的时候设置children,这是children是一个数组,数组里是路由对象,这个children的组件就会渲染在它父组件的<router-view>中,注意children中的子路由的对象中的path属性的内容不加/,如果加/ 会被解析为根路由。
{
path:'/detail',
component: detail,
children:[
{
path:'play',
component:play
},{
path:"course",
component:course
}
]
},