一、router理解
1、vue-router的理解:vue的一个插件库,专门用来实现SPA应用
2、对SPA的理解:
- 单页面web应用
- 整个应用只有一个完整的页面
- 单机页面中的导航,链接不会刷新页面,只会做页面的局部更新
- 数据需要通过ajax请求获取
3、路由(route)的理解
-
(1)什么是路由: 一个路由就是一组映射关系(key-value) key为路径,value可能是function或者component(组件) (2)路由分类 ---后端路由 1)理解:value是function,用于处理客户端提交的请求 2)工作过程:服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据 ---前端路由 1)理解:value是component(组件),用于展示页面内容 2)工作过程:当浏览器的路径改变时,对应的组件就会显示
二、 路由基本使用 1、安装vue-router,命令:
npm i vue-router
2、应用插件:
// 引入vue-router import VueRouter from 'vue-router'
Vue.user(VueRouter)//增加了一个$route
3、编写router的配置项
// 引入vue-router
import VueRouter from 'vue-router'
// 引入组件
import About from '../components/About'
import Home from '../components/Home'
// 创建一个路由器并暴露
export default new VueRouter({ routes:[ { path:'/about', //路径 component:About //对应组件 }, { path:'/home', component:Home } ] })
4、实现切换(active-class可配置高亮样式):router-link
<router-link active-class="active" class="list-group-item" to="/about">About</router-link>
5、指定展示位置:router-view(类比插槽)
<router-view></router-view>
路由使用的几个注意点
1)路由组件通常存放在pages文件夹中,一般组件通常存放在components文件夹中
2)通过切换,‘隐藏’的路由组件,默认是被销毁了的,需要的时候再去挂载
3)每个组件都有自己的$route属性,里面存储的是自己的路由信息
4)整个应用只有一个router,可以通过组件的$router属性获取到信息
三 多级路由
配置路由规则,使用children配置项(谁需要组件给谁添加children)
export default new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home, children:[//通过children配置子级路由 { path:'message',//此处一定不要写:/message component:Message }, { path:'news', component:News }, ] } ] })
2、跳转(要写完整路径---带着他的父辈)
<router-link active-class="active" to="/home/news">News</router-link>
四 路由的参数
4.1 路由的query参数
传递参数
<router-link :to="/home/message/detail?id={m.id}&title={m.title}">{{m.title}}</router-link>
`<router-link :to="{
path:'/home/message/detail',
query:{
id:m.id,
title:m.title
}
}">
跳转
</router-link>
接收参数 this.route.query.id/this.$route.query.title)`
4.2 命名路由
作用:可以简化路由跳转
如何使用:
--给路由命名
routes:[ { path:'/home', component:Home, children:[ { name:'xiaoxi', path:'message', component:Message, children:[ { name:'xiangqing', path:'detail', component:Detail, meta:{ isAuth:true, title:'详情' } } }, ] } ]
路由中meta配置项: 当需要配置一些其他的不信息时,就可以使用meta配置,比如控制权限、显示组件信息……
(2)简化跳转:
<-- 简化前 -->
<router-link to="/home/message/detail">About</router-link>
<-- 简化后 -->
<router-link :to="{name:'xiangqing'}">About</router-link>
<-- 简化写法配合参数 -->
<router-link :to="{ name:'xiangqing', query:{ id:m.id, title:m.title } }"> 跳转 </router-link>
4.3 路由的params参数
配置路由,声明接收params参数
routes:[ { path:'/home', component:Home, children:[ { name:'xiaoxi', path:'message', component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符号声明接收params参数 component:Detail, } }, ] } ]
传递参数
<-- 跳转路由并携带params参数,to的字符串写法 -->
<router-link :to="/home/message/detail/{m.title}">跳转</router-link>;
<-- 跳转路由并携带params参数,to的对象写法 -->
`<router-link :to="{
name:'xiangqing',
params:{
id:m.id,
title:m.title
}
}">
跳转
</router-link>`
注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置(路由命名)
接收参数
$route.params.xxx($route.params.id/$route.params.title)