最近本身在寫一個vue的小型管理系統,在瀏覽器中看到的路由都是帶有#的,非常很差看。爲了解決此問題,你們通常都會想到:mode: 'history'。但是在開發階段沒有問題,可是一旦build打包後,訪問並刷新瀏覽器後,頁面就會報404的錯誤,爲了解決打包後刷新瀏覽器報404的問題,若是使用nginx的話,還須要作以下配置。下面貼出完整的解決方案。php
在new Router()的下一行添加上:mode: 'history',html
import Vue from 'vue' import Router from 'vue-router' import Utils from '@/js/utils.js' import Login from '@/components/Login' import PerInfo from '@/components/perInfo/perInfo' import Home from '@/components/Home' import Dashboard from '@/components/Dashboard' import UserList from '@/components/user/userList' import UserAdd from '@/components/user/userAdd' Vue.use(Router) const router = new Router({ mode: 'history', //去掉url中的# routes: [ { path: '/', name: 'home', component: Home, redirect: '/login', // iconCls: 'iconfont icon-home', //圖標樣式class children: [ {path: '/home', component: Dashboard, name: '首頁'} ] }, { path: '/login', name: '登陸', component: Login }, { path: '/home', name: '儀表盤', component: Dashboard }, { path: '/user', component: Home, name: '用戶管理', children: [ {path: '/user/list', component: UserList, name: '用戶列表'}, {path: '/user/add', component: UserAdd, name: '添加用戶'} ] }, { path: '/', component: Home, name: '系統設置', children:[ {path: '/setting/perInfo', component: PerInfo, name: '我的信息'} ] } ] }) router.beforeEach((to, from, next) => { console.log('開始頁面切換'); console.log(to.fullPath) var tempId = Utils.getCookie('temp-id'); var userInfo = sessionStorage.getItem('ssm_u_info'); if(to.fullPath != '/login' && (tempId == null || tempId == '' || userInfo == null || userInfo == '')){ window.location.href = '/login'; } next(); }); export default router
my-vue.conf文件內容:vue
server { listen 80; server_name my.vue.com; charset utf-8; location / { root /Users/libo/Documents/workspace/Vue-me/my-project/dist; index index.html index.htm index.php; try_files $uri $uri/ /index.html; } location ^~ /ssm_project/ { proxy_pass http://127.0.0.1:8081; proxy_cookie_path /127.0.0.1:8081/ /; proxy_pass_header Set-Cookie; proxy_set_header Host 127.0.0.1:8081; } }
在/private/etc下的hosts文件添加以下內容:nginx
127.0.0.1 my.vue.comvue-router
在命令行執行sudo nginx命令,以啓動nginx服務,便可訪問,在瀏覽器中輸入my.vue.com,回車後頁面以下瀏覽器
登陸系統,點擊用戶列表菜單:cookie
此時此刻,不管當前路由顯示的是在登陸頁仍是其餘頁面,再刷新瀏覽器,頁面也不會報404了,大功告成!session
須要購買阿里雲產品的,能夠點擊此連接領取紅包,優惠購買哦,領取後一個月內有效: https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=fp9ccf07ui