无法弄清楚 vue-router 是如何工作的

Cannot figure out how vue-router works

我有一个带有以下路由器的 Vue.js 项目:

import Vue from 'vue';
import Router from 'vue-router';
import Overview from '@/components/Overview';
import Experiment from '@/components/ForExperiment';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      redirect: 'test',
    },
    {
      path: '/overview',
      component: Overview,
    },
    {
      path: '/overview/from/:from/to/:to',
      name: 'overview',
      component: Overview,
    },
    //... some other urls goes here.
    {
      path: '/test',
      name: 'test',
      component: Experiment,
    },
  ],
});

如果我在浏览器中打开 http://localhost:8080,我将被重定向到 http://localhost:8080/#/test。为什么不只是 http://localhost:8080/test? “#”符号从何而来?

为什么我打开 http://localhost:8080/test 会被重定向到 http://localhost:8080/test#/test

更奇怪的是,如果我打开 http://localhost:8080/overview,我将被重定向到 http://localhost:8080/overview#/test,因此不会显示 Overview 组件。

是什么导致了这些奇怪的效果?

Vue 路由器有 different modes。检测到浏览器时的默认模式是 hash。当前路由由 url 的哈希部分确定。这种方法的好处是不需要服务器端配置。所有 url 都指向相同的资源(例如路线),您可以将其制作为 index.html 文件。

您可以将此模式更改为 history。历史模式使用浏览器的历史api。它只适用于最近的浏览器,但 support 目前应该不是问题。它还需要服务器端配置,因为您需要在内部将路由器 urls 重写为同一文件。如果您不这样做,刷新页面将显示 404 页面,而不是您要查看的页面。

vue-router 默认模式是散列模式,这就是为什么您会在 URL 上看到 #。它使用 URL 哈希来模拟完整的 URL,如果它发生变化则无需重新加载页面。

要去掉散列,我们可以使用vue-router历史模式。像这样更改 mode

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

这利用了 History API

如果您想使用历史记录模式,您需要更改您的服务器配置。 Vue Router 文档有一些示例 here.

vue 路由器默认为 hash mode。要让 url 进入 http://localhost:8080/test,您需要进入 history 模式。这样做是因为默认情况下 Web 服务器未设置为将所有请求重定向到一个 html 文件。 hash 模式用于每个文档:

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes.

将您的路由器更改为此以获得 history 模式。但是你需要 configure NGINX or Apache2 将所有请求重定向到你的 vue 代码

const router = new VueRouter({
  mode: 'history', // Add this to your router
  routes: [...]
})