首页 > 其他 > 详细

vue路由的两种模式,hash与history的区别

时间:2019-12-13 18:57:10      阅读:95      评论:0      收藏:0      [点我收藏+]

1.直观区别:

    hash模式url带#号,history模式不带#号。

2.深层区别:

     hash模式url里面永远带着#号,我们在开发当中默认使用这个模式。

     如果用户考虑url的规范那么就需要使用history模式,因为history模式没有#号,是个正常的url适合推广宣传

     功能也有区别,比如我们在开发app的时候有分享页面,那么这个分享出去的页面就是用vue或是react做的,

     咱们把这个页面分享到第三方的app里,有的app里面url是不允许带有#号的,所以要将#号去除那么就要使用history模式

    但是使用history模式还有一个问题就是,在访问二级页面的时候,做刷新操作,会出现404错误,那么就需要和后端人配合让他配置一下apache或是nginx的url重定向,重定向到你的首页路由上就ok啦。

 

路由模式配置:

1 export default new Router({
2     // mode: ‘history‘,
3     mode: ‘hash‘,
4     routes
5 })

如果是 history模式需要后端配合解决刷新404问题 这里以Node 后台为例:

 1 const Koa = require(‘koa‘)
 2 const Router = require(‘koa-router‘);
 3 const static = require(‘koa-static‘)
 4 const fs = require(‘fs‘);
 5 const app = new Koa();
 6 const router = new Router();
 7 
 8 let str;
 9 fs.readFile(‘../dist/index.html‘, "utf-8", (err, data) => {
10     if (err) {
11         ctx.body = "error found"
12     }
13     str = data.toString();
14 })
15 
16 // 解决vue 路由在 history刷新 404情况
17 router.get(‘*‘, async(ctx, next) => {
18     if (ctx.url !== "/index.html") {
19         console.log("在这里返回")
20         ctx.body = str;
21     } 
22 })
23 
24 app.use(static("../dist/"));
25 app.use(router.routes()) //启动路由
26 app.use(router.allowedMethods());
27 
28 
29 app.listen(8989, () => {
30     console.log("监听服务器地址:127.0.0.1:8989");
31 })

vue路由的两种模式,hash与history的区别

原文:https://www.cnblogs.com/lbcxq/p/12036788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!