vue-痴汉的路引-路由
**前言:本文仅用供学习之后理清知识点查看,详细知识点建议访问官方网站:**https://router.vuejs.org/
1.SPA概念
单页面应用(SinglePage Web Application,SPA) | 多页面应用(MultiPageApplication,MPA) | |
---|---|---|
组成 | 一个外壳和多个页面片段组成 | 多个完整页面构成 |
资源共用(css,js) | 共用,只需在外壳部分加载 | 不共用,每个页面都需要加载 |
刷新方式 | 页面局部刷新或更改 | 整页刷新 |
url模式 | a.com/#/pageone a.com/#/pagetwo |
a.com/pageone.html a.com/pagetwo.html |
用户体验 | 页面片段间的切换快,用户体验良好 | 页面切换加载缓慢,流畅度不够,用户体验比较差 |
转场动画 | 容易实现 | 无法实现 |
数据传递 | 容易 | 依赖url传参、或者cookie、localStorage等 |
搜索引擎优化(SEO) | 需要单独方案、实现较为困难、不利于SEO检索、可利用服务器端渲染(SSR)优化 | 实现方法简易 |
试用范围 | 高要求的体验度、追求界面流畅的应用 | 试用于追求高度支持搜索引擎的应用 |
开发成本 | 较高,常需借助专业的框架 | 较低,但页面重复代码多 |
维护成本 | 相对容易 | 相对复杂 |
vue-router
-
开始
const Foo = { tempalte: '<div>foo</div>'} const Bar = { template: '<div>bar</div>'} const routes = [ {path: '/foo', component: Foo }, {path: '/bar', component: Bar } ] const router = new VueRouter({ routes //(缩写)相当于 routes:routes }) // APP.vue 留有<route-view>为页面插入位置
-
动态路由匹配
-
嵌套路由
-
编程式导航(js跳转)vs 声明式
-
路径
//点击事件 this.$router.push(`/detail/${id}`)
// index.js { path: '/detail/:myid', component: Detail, },
// 跳转页面通过 this.$route.params.myid 获取id
-
路由名字
// 点击事件 this.$router.push({ name: 'huang', params: { myid: id } })
// index.js { path: '/detail/:myid', component: Detail, name: 'huang' },
// 跳转页面通过 this.$route.params.myid 获取id
-
query方式跳转详情
// 点击事件 this.$router.push(`/detail?id=${id}`)
// index.js { path: '/detail', component: Detail },
// 跳转页面通过 this.$route.query.id 获取id
-
-
命名路由($route.name获取命名路由的名字)
-
重定向和别名
const router = new VueRouter({ routes:[ {path:'/a',redirect:'/b'} ] })
const router = new VueRouter({ routes:[ {path:'/a',comppnent: A, alias: '/b'} ] })
-
HTML5 History模式
vue支持两种模式
- hash #/home
- history /home
-
路由守卫&路由拦截
-
全局拦截
router.beforeEach((to, from, next) => { const auth = ['/center', '/order', '/money', '/card'] if (auth.includes(to.fullPath)) { if (!localStorage.getItem('token')) { next('/login') } else { next() } } else { next() } })
-
单个拦截
// 在需要验证的页面里 beforeRouteEnter (to, from, next) { if (!localStorage.getItem('token')) { next('/login') } else { next() } }
-
-
路由懒加载
const Foo = () => import('./Foo.vue')
在路由配置中什么都不需要改变,只需要像往常一样使用Foo:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo } ] })
反向代理
官方文档:https://cli.vuejs.org/zh/config/#devserver
在vue.config.js中配置
module.exports = {
devServer: {
proxy: {
"/ajax":{
target: "https://m.maoyan.com",
changeOrigin: true
}
}
}
}
转载:https://blog.csdn.net/qq_45902611/article/details/116357901
查看评论