vue3 + vite 下vue-router history模式实践

2,670 阅读1分钟

一、项目配置

1. router/index配置

注:import.meta.env.BASE_URLvite.config.js 中根路径base字段,请见下面vite.config.js文件位置

import { createRouter, createWebHistory } from "vue-router";


const routes = [
  // 设置根目录跳转重定向
  {
    path: '/',
    name: 'home',
    redirect: '/home',
  },
  {
    path: "/home",
    name: "demo",
    meta: { title: '大模型闪电验证DEMO' },
    component: HomeView,
  },
  ...
  ...
  // 设置全路由兜底配置,一般用户错误页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    meta: { title: '404' },
    component: () => import('@/views/common/NotFound.vue')
  }
]


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})


export default router;

2. main.js

main.js中文件中引入router文件,

import router from "./router";

const app = createApp(App);

app.use(router)
...
...
app.mount("#app");

3. vite.config.js 配置

import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import vueSetupExtend from 'vite-plugin-vue-setup-extend'

// https://vitejs.dev/config/
export default defineConfig({
  base: 'chat-demo', // 根目录 =》 import.meta.env.BASE_URL
  plugins: [vue(), vueJsx(), vueSetupExtend()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  optimizeDeps: {
    //
  },
  css: {
    preprocessorOptions: {
      scss: {
        // additionalData: '@import "./src/assets/base.scss";'
      }
    }
  },
  ...
  ...
});

二、服务端nginx配置

1. nginx.conf 配置

这里我使用的相对路径alias,你也可以使用绝对路径root, try_files 需要配置,这是history模式设置的关键,详见下方学习和参考文档

http {
    server {
        listen 443 ssl;
        server_name XXX.com;
        ...
        ...

        #大模型闪电验证Demo
        location /chat-demo {
            alias /myserver/chat-demo;
            try_files $uri $uri/ /chat-demo/index.html;
            index index.html index.htm;
            expires -1;
        }

    }
    ...
    ...

}

三、学习和参考文档

vue-router官方文档

nginx中文官网

nginx配置选项try_files详解

Nginx-location路由规则配置详解

nginx root与alias