Skip to content

Router 配置

Vue.js 的官方路由

不同的历史模式

Hash 模式 vs HTML5 模式 不同之处 v4.0

bash
$ http://localhost/#/user/id
$ http://localhost/user/id
$ http://localhost/#/user/id
$ http://localhost/user/id

启用 HTML5 模式

提示

服务器没有配置,直接访问 http://localhost/user/id 会返回 404 页面

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

const router = createRouter({
  history: createWebHistory(), 
  routes: [
    // ...
  ],
})
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(), 
  routes: [
    // ...
  ],
})

服务器配置

nginx 配置

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

Apache 配置

apache
<IfModule mod_negotiation.c>
  Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
<IfModule mod_negotiation.c>
  Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

也可以使用 FallbackResource 代替 mod_rewrite

导航守卫的使用

全局 前置守卫 & 后置钩子

ts
const whiteList: string[] = ['/login', '/test'] // 不重定向白名单
router.beforeEach(async (to, from, next) => {
  const appStore = useAppStore()
  const permissionStore = usePermissionStore()

  const userInfo = useStorage(appStore.userInfo, null)

  if (userInfo.value) {
    // 如果登录,则重定向到主页
    next({ path: '/' })
  }
  else {
    permissionStore.isAddRouters = false
    if (whiteList.includes(to.path)) {
      next()
    }
    else {
      // 否则全部重定向到登录页
      next({
        path: '/login',
        query: {
          redirect: to.path,
        },
      })
    }
  }
})

router.afterEach((to) => {
  document.title = getPageTitle(
    to.meta.title,
    import.meta.env.YANG_APP_TITLE || useAppStore().title
  )
})
const whiteList: string[] = ['/login', '/test'] // 不重定向白名单
router.beforeEach(async (to, from, next) => {
  const appStore = useAppStore()
  const permissionStore = usePermissionStore()

  const userInfo = useStorage(appStore.userInfo, null)

  if (userInfo.value) {
    // 如果登录,则重定向到主页
    next({ path: '/' })
  }
  else {
    permissionStore.isAddRouters = false
    if (whiteList.includes(to.path)) {
      next()
    }
    else {
      // 否则全部重定向到登录页
      next({
        path: '/login',
        query: {
          redirect: to.path,
        },
      })
    }
  }
})

router.afterEach((to) => {
  document.title = getPageTitle(
    to.meta.title,
    import.meta.env.YANG_APP_TITLE || useAppStore().title
  )
})