vue prod 環境 怎么去掉#!


 

 眾所周知,vue-router有兩種模式,hash模式和history模式。

    

hash模式

hash模式背后的原理是onhashchange事件,可以在window對象上監聽這個事件:

window.onhashchange = function(event){ console.log(event.oldURL, event.newURL); let hash = location.hash.slice(1); document.body.style.color = hash; }

history路由

隨着history api的到來,前端路由開始進化了,前面的hashchange,你只能改變#后面的url片段,而history api則給了前端完全的自由

history api可以分為兩大部分,切換和修改,

 

切換歷史狀態

包括back,forward,go三個方法,對應瀏覽器的前進,后退,跳轉操作,有同學說了,(谷歌)瀏覽器只有前進和后退,沒有跳轉,嗯,在前進后退上長按鼠標,會出來所有當前窗口的歷史記錄,從而可以跳轉(也許叫跳更合適):

history.go(-2);//后退兩次 history.go(2);//前進兩次 history.back(); //后退 hsitory.forward(); //前進

修改歷史狀態

包括了pushState,replaceState兩個方法,這兩個方法接收三個參數:stateObj,title,url

history.pushState({color:'red'}, 'red', 'red'}) window.onpopstate = function(event){ console.log(event.state) if(event.state && event.state.color === 'red'){ document.body.style.color = 'red'; } } history.back(); history.forward();

通過pushstate把頁面的狀態保存在state對象中,當頁面的url再變回這個url時,可以通過event.state取到這個state對象,從而可以對頁面狀態進行還原,這里的頁面狀態就是頁面字體顏色,其實滾動條的位置,閱讀進度,組件的開關的這些頁面狀態都可以存儲到state的里面。

history模式怕啥

通過history api,我們丟掉了丑陋的#,但是它也有個毛病:
不怕前進,不怕后退,就怕刷新f5,(如果后端沒有准備的話),因為刷新是實實在在地去請求服務器的,不玩虛的。

在hash模式下,前端路由修改的是#中的信息,而瀏覽器請求時是不帶它玩的,所以沒有問題.但是在history下,你可以自由的修改path,當刷新時,如果服務器中沒有相應的響應或者資源,會分分鍾刷出一個404來。

 

hash 模式  改為 history 模式 在 nginx 中怎么配置

 

src/router/index.js

router = new VueRouter({
     hashbang: false  history: true
      routes: [
    {
     path: '/',
    redirect: '/pages/'
    },

注意, config/index.js

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',      hash 模式會默認的在此處  添加為 assetsPublicPath: './',
 productionSourceMap: true,   
 ...
}
}

   前段時間,我們自己的項目中在使用vue 的時候,遇到了這個問題路由中會有#!, 老板說看着這個很不爽,

可是把模式改為history(或者有些, hashbang: False , history :True) , 在nginx 中把location 修改了,還是不行,

最后把 config 中的 index.js中的     assetsPublicPath: './', 修改為 assetsPublicPath: '/', 就可以了 。

個人猜測 :vue 默認的mode hash 模式   在項目運行時會根據項目中路徑的分發     此處 默認添加為 assetsPublicPath: './',

 

同時還要在nginx  環境中配置

 

server {
    listen 0.0.0.0:12345;

    location / {
        root /home/我的應用跟目錄;
        try_files $uri $uri/ /index.html =404;
    }

    error_page 404 /index.html
}

 

 

哈哈, 這樣就解決了,

文檔

 


免責聲明!

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



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