VUE路由去除#問題


最近自己在寫一個vue的小型管理系統,在瀏覽器中看到的路由都是帶有#的,很是不好看。為了解決此問題,大家一般都會想到:mode: 'history'。可是在開發階段沒有問題,但是一旦build打包后,訪問並刷新瀏覽器后,頁面就會報404的錯誤,為了解決打包后刷新瀏覽器報404的問題,如果使用nginx的話,還需要做如下配置。下面貼出完整的解決方案。

1、路由代碼中添加mode:'history'

在new Router()的下一行添加上:mode: 'history',

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

2、nginx配置

2.1、在nginx目錄下新建 vhosts目錄

2.2、在vhosts目錄下新建my-vue.conf配置文件

2.3、在nginx的配置文件my-vue.conf中添加:try_files $uri $uri/ /index.html;

my-vue.conf文件內容:

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

 2.4、在nginx目錄下的nginx.conf http下的最后添加如下代碼

 

 2.5、配置hosts文件

在/private/etc下的hosts文件添加如下內容:

   127.0.0.1   my.vue.com

3、訪問效果

在命令行執行sudo nginx命令,以啟動nginx服務,即可訪問,在瀏覽器中輸入my.vue.com,回車后頁面如下

登錄系統,點擊用戶列表菜單:

此時此刻,無論當前路由顯示的是在登錄頁還是其他頁面,再刷新瀏覽器,頁面也不會報404了,大功告成!

 

需要購買阿里雲產品的,可以點擊此鏈接領取紅包,優惠購買哦,領取后一個月內有效https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=fp9ccf07


免責聲明!

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



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