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
}

哈哈, 这样就解决了,

文档

原文地址:https://www.cnblogs.com/win-lin08/p/7903007.html