目录
路由的简介
vue-rooter:是vue的一个插件库,专门用来实现SPA应用
对SPA应用的理解
- 单页 Web 应用(single page web application,SPA)。
- 整个应用只有一个完整的页面 index.html。
- 点击页面中的导航链接不会刷新页面,只会做页面的局部更新。
- 数据需要通过 ajax 请求获取。
路由的理解
什么是路由?
- 路由就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
- key 为路径, value 可能是 function 或 component组件
- vue 的一个插件库(vue-router),专门用来实现 SPA 应用
路由分类
-
后端路由
- value 是 function, 用于处理客户端提交的请求。(node.js)
- 工作过程:服务器接收到一个请求时, 根据请求路径找到匹配的函数来处理请求, 返回响应数据。
-
前端路由
- key是路径,value是组件component,用于展示页面内容。
- 工作过程:当浏览器的路径改变时, 对应的组件就会显示。
路由基本使用
注意:vue2中,要用vue-router的3版本,vue3中,要用vue-router的4版本,否则会报错
使用步骤
-
安装vue-router,命令:
npm i vue-router
-
编写router配置项:src/router/index.js
//引入VueRouter import VueRouter from 'vue-router' //引入Luyou 组件 import About from '../components/About' import Home from '../components/Home' //创建router实例对象,去管理一组一组的路由规则 const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) //暴露router export default router
-
应用插件:
Vue.use(VueRouter)
和引入路由器router -
实现切换(active-class可配置高亮样式)
<router-link active-class="active" to="/about">About</router-link>
<router-link>
Vue中借助router-link标签实现路由的切换 ,to=“/xxx”
是展示的路径,active-class
是当你点击这个的时候可展示的高亮样式 -
指定展示位置
<router-view></router-view>
图示代码:
注意点
-
路由组件通常存放在
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 } ] } ]
-
跳转(要写完整路径):
<router-link to="/home/news">News</router-link>
主要代码:
写两个Home里面的路由组件
src/router/index.js
配置路由器
// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About.vue'
import Home from '../pages/Home.vue'
import News from '../pages/News.vue'
import Message from '../pages/Message.vue'
// 创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News,
},
{
path:'message',
component:Message,
}
]
},
]
})
src/pages/Home.vue
是在Home里面嵌套一个路由,就要在Home.vue里面写结构,里面的路由部分修改
<template>
<div>
<h2>我是Home的内容</h2>
<div>
<h2>Home组件内容</h2>
<div>
<ul class="nav nav-tabs">
<li>
<router-link class="list-group-item" active-class="active" to="/home/news" >News</router-link
>
<