vue路由的兩種模式,hash與history的區別


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 })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM