一、单页面应用与前端路由
- 单页面应用SPA介绍
前端路由的两种实现方式
已有项目中手动安装VueRouter
- npm i vue-router —save
项目构建过程中安装VueRouter
src->router->index.js
引入VueRouter插件
import Vue from "vue"
import VueRouter from "vue-router"
定义路由规则的数组
const routes = []
创建VueRouter对象 ```javascript const router = new VueRouter({ routes, mode: “history”
})
- 导出VueRouter对象
```javascript
export default router
三、VueRouter开发第一个Demo
- 创建被路由的组件
-
四、路由重定向与组件懒加载
路由重定向
- redirect指向的是在router数组中定义的子路由
{
path: "/",
redirect: "/home"
},
- redirect指向的是在router数组中定义的子路由
路由组件的懒加载
嵌套路由是指页面的子路由,使用children配置
{
path: "/home",
component: Home,
children: [
{
path: "",
component: Article
},
{
path: 'news',
component: News
},
]
}
六、动态路由的配置与实现
含义
- 动态路由可以传递参数,根据不同的参数组件可以显示不同的内容
- 动态路由可以实现路由导航,也就是匹配一个路由规则,从而显示路由规则的组件
动态路由的多段匹配 | 路由规则 | 匹配url | $route.params对象 | 匹配规则含义 | | —- | —- | —- | —- | | /article/:id | /article/1 | {id:1} | id=1的文章 | | /article/:id/reader/:num | /article/1/reader/2 | {id:1,num:2} | id=1的文章的第2位读者信息 |
动态路由的正则匹配 | 路由规则 | 匹配规则含义 | | —- | —- | | /article/:id | 参数id必须传,参数可以是数字也可以是字符串,即/article/1和/article/abc都匹配这个路由规则 | | /article/:id? | 参数id可以传,可以不传,即/article/1和/article都匹配这个路由规则 | | /article/:id(\d+) | 参数id必须传,并且只能是数字,如:/article/1 | | /article/* | 星号表示匹配任意路径,即/article/abc和//article/abe/def都可以匹配这条路由规则 |
七、命名路由与命名视图
什么是命名视图
什么是编程式导航
使用path路由跳转并传参数
<router-link to="/home/article/1">id为1的文章</router-link>
- 页面获取传递的参数【$route】
<h2>这里是id={{ $route.params.id }}读者的文章组件</h2>
使用命名路由并传参
<router-link :to="{ name: 'article', params: { id: 2 } }"
>id为2的文章</router-link>
- 获取页面传递的参数【$route】
<h2>这里是id={{ $route.query.id }}读者的文章组件</h2>