Vue.js + Vite下如何移除base路径实现外部链接跳转
问题描述
我在Vite配置里把base设为'/v2/',导致所有URL都带上了/v2/前缀。现在点击外部链接时,希望跳转到localhost:3000/profile/user,但实际跳转路径是localhost:3000/v2/profile/user,得把外部链接里的/v2/前缀去掉。我试过用路由导航守卫来处理,相关代码如下:
Vite配置代码
import { fileURLToPath, URL } from 'node:url'; import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ plugins: [vue()], base: '/v2/', server: { port: 3000, }, resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, });
Vue Router相关代码
// .... setup() { const router = useRouter(); const state = reactive({ tabs: [ { name: 'Booking', icon: 'fa-regular fa-calendar', external: false, }, { name: 'Profil', icon: 'fa-solid fa-user', external: true, link: 'profile/user', }], currentTab: 'Dashboard', }); function handleClickTab({ tab }) { const isExternal = get(tab, 'external'); const tabName = get(tab, 'name'); const tabLink = get(tab, 'link'); if (isExternal) { router.push(tabLink); return; } router.push({ name: tabName }); state.currentTab = tabName; } return { ...toRefs(state), handleClickTab, }; }
解决方案
你现在用router.push()处理外部链接的方式不对——router.push()是Vue路由内部跳转的方法,会自动带上Vite配置的base前缀。针对外部路径,直接用原生页面跳转方法即可,无需通过路由处理。
方法1:修改点击事件逻辑(最直接)
把外部链接的跳转逻辑换成原生window.location.href:
function handleClickTab({ tab }) { const isExternal = get(tab, 'external'); const tabName = get(tab, 'name'); const tabLink = get(tab, 'link'); if (isExternal) { // 直接跳转,不带/v2/前缀 window.location.href = `/${tabLink}`; return; } router.push({ name: tabName }); state.currentTab = tabName; }
如果外部链接是跨域名的完整地址(比如https://other-domain.com/profile/user),直接写全链接后用window.location.href = tabLink即可。
方法2:全局路由守卫处理(适合批量场景)
如果需要统一处理所有外部路由,可以在全局前置守卫里判断并重定向:
router.beforeEach((to, from, next) => { // 给需要跳转的路由meta标记external if (to.meta?.external) { // 移除/v2/前缀后跳转 window.location.href = to.fullPath.replace('/v2/', '/'); return; } next(); });
这种方式需要给对应路由添加meta: { external: true }的标记,不过不如第一种方法直观,推荐优先用方法1。
内容的提问来源于stack exchange,提问作者Alexis
相关产品推荐
相关产品推荐

