单页应用程序: SPA
单页面应用(SPA): 所有功能在一个html页面上实现 (多页面应用程序MPA)
优点:
不整个刷新页面,每次请求仅获取需要的部分,用户体验更好
数据传递容易, 开发效率高
缺点:
开发成本高(需要学习专门知识 - 路由)
首次加载会比较慢一点。不利于seo
前端Vue中的路由是路径和组件的映射关系
前端Vue中的路由是路径和组件的映射关系
vue-router基本使用(5 + 2)
-
5 个 基础步骤
-
【1】下载vue-router模块到当前工程,版本3.5.3
yarn add vue-router@3.5.3
-
【2、3】在main.js(或
router/index.js中,并导入vue、导出router)中引入VueRouter函数,并添加到Vue.use()身上import VueRouter from 'vue-router' Vue.use(VueRouter)
-
【4、5】创建路由对象,并将路由对象注入到new Vue实例中(main.js中)(导入router)
const router = new VueRouter()
-
-
2 个 核心步骤
-
配置路由规则 (在创建路由对象时添加)(路径和组件的对应,什么路径应该渲染什么组件)
- router:整个全局最大的路由实例,唯一
- routes:路由规则列表,数组,有多条路由规则
[{},{},{}]
- route:一条路由规则,对象,记录了路径和组件的对应关系
{path:路径,component:组件}
import Find from '@/views/Find.vue' //@指代src目录,可以直接从src出发找文件 import My from '../views/My.vue' import Part from '../views/Part.vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const router = new VueRouter({ routes:[ { path: '/', redirect: '/find' }, //重定向,默认显示页面 { path:'/find',component:Find }, //一般直接设置为/,省略上面的重定向 { path:'/my',component:My }, { path:'/part',component:Part }, { path: '*', component: Page404 }, //要放在最后,如果都没匹配上,则404页面 { path: '/', component: Layout, //一级路由 //二级路由需要在以及路由处重定向 children: [ //配置二级路由,二级路由点进去的内容,是一级路由 { path: '/article',component:Article }, { path: '/collect',component:Collect }, { path: '/like',component:Like }, { path: '/user',component:User } ] } ] })
-
指定路由出口 router-view (App.vue中)(决定了匹配的组件在哪里渲染)
<router-view></router-view> 利用keep-alive便签可以缓存组件内容,使得切换时不会摧毁。 之后组件会多出2个钩子,分别是activated和deactivated <keep-alive> <router-view></router-view> </keep-alive>
-
导航方式总结:
配置动态路由
{ path: '/detail/:id', component: Detail },
声明式导航(a标签实现)
<!-- 传参 -->
<router-link to="/test1/参数">跳转到路由并传参</router-link>
<!-- 接收 -->
<p>{{$route.params.id}}</p>
编程式导航(没有a标签时)
<div @click="$router.push(`/test1/${id (参数动态控制) }`)">跳转到路由并传参</div>
<p>{{$route.params.id}}</p>