VUE3(十八)vue 路由history 模式去掉 URL 中的 # (nginx)


這部分內容比較少。其實更多的是參考一下vue-router4的官方文檔就好。

但是,這部分還是拿出來說一下。

1:router.ts

// 官方文檔:https://vue3js.cn/router4/guide/#html
// 引入vue-router對象
import { createRouter, createWebHistory, createWebHashHistory, ErrorHandler } from "vue-router";
/**
 * 定義路由數組
 */
const routes = [
  {// 404路由
    path: '/404',
    name: '404',
    component: ()=>import('/@/views/404.vue')
  },
];
 
/**
 * 創建路由
 */
const router = createRouter({
  // hash模式:createWebHashHistory,
  // history模式:createWebHistory
  history: createWebHistory("/"),
  // history:createWebHashHistory("/#"),
  routes,
});
 
/**
 * 路由錯誤回調
 */
router.onError((handler: ErrorHandler) => {
  console.log("error:", handler);
});
 
/**
 * 輸出對象
 */
export default router;

2:后端服務器配置(我這里使用的是nginx):

這部分請參考官方文檔:

https://next.router.vuejs.org/guide/essentials/history-mode.html

location / {
  try_files $uri $uri/ /index.html;
}

3:請求鏈接書寫方式

但是,去掉#之后的路由在配合php框架使用的時候可能會有問題,就是這個鏈接不知道該去后端還是去前端的路由。

解決這個問題其實也很簡單。

就是在請求連接前加入index.php,這樣前端連接在跳轉的時候就不會出問題。

如下所示:

// 引入公共js文件

import request from "/@/hooks/request";
 
/**
 * @name: 提交留言
 * @author: camellia
 * @email: guanchao_gc@qq.com
 * @date: 2021-03-01 
 */
export const putmessage = (data: any) => request.get("/index.php/about/putmessage", data, '');

有好的建議,請在下方輸入你的評論。

歡迎訪問個人博客
https://guanchao.site

歡迎訪問小程序:

在這里插入圖片描述


免責聲明!

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



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