vue3 路由开启history模式

vue yekong 1022℃

vue3开发的 数据可视化大屏 项目中客户觉得地址中带有#号太丑了,所以需要开启history模式,来去掉#号。

要在Vue 3中开启路由的history模式,需要进行以下步骤:

安装Vue Router

安装Vue Router:确保已经安装了Vue Router依赖包。可以使用npm或者yarn进行安装:

npm install vue-router
# 或
yarn add vue-router

创建路由器实例

创建路由器实例:在项目中创建一个新的文件(通常命名为router.jsindex.js),并导入Vue和Vue Router。然后创建一个新的路由器实例,并定义路由规则。

// router.js

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

// 导入路由组件
import Home from './components/Home.vue';
import About from './components/About.vue';

const routes = [
  {
    path: '/',
    component: Home
  },
  {
    path: '/about',
    component: About
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

在Vue应用中使用路由器

在Vue应用中使用路由器:在Vue应用的主入口文件(通常是main.js)中导入路由器实例,并将其作为router选项传递给Vue应用。

// main.js

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

createApp(App)
  .use(router)
  .mount('#app');

配置服务器支持

配置服务器支持:如果你的应用程序是部署到一个服务器上的,确保服务器能够处理基于history模式的路由。对于大多数服务器,需要配置一个通配符路由,以便在任何URL请求下都返回应用的入口文件。

  • Apache服务器(使用.htaccess文件):
    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
    </IfModule>
    
  • Nginx服务器:
    location / {
      try_files $uri $uri/ /index.html;
    }
    

现在你的Vue 3应用程序已经配置了使用history模式的路由。在浏览器中访问URL时,路由将会处理并加载相应的组件,而无需在URL中包含#符号。注意,在使用history模式时,确保你的服务器正确地处理路由请求,并在不存在的路由时返回应用的入口文件,以避免404错误。

喜欢 (0)