Vue路由无法直接跳转外部链接,必须用原生方式:当前页用window.location.href,新标签页推荐window.open(url, '_blank', 'noopener,noreferrer'),模板中用标签并添加rel="noopener noreferrer"。

Vue 路由(vue-router)本身只负责管理应用内部的路由跳转,不能直接用 router.push() 打开外部链接。想跳转到外部网站(比如 https://example.com),必须绕过 vue-router,使用原生浏览器能力。
内部跳转:用 router.push()
适用于跳转到本应用内的页面,如 `/home`、 `/user/123`:
- 编程式跳转:
this.$router.push('/about')(Vue 2)或router.push('/about')(Vue 3 Composition API) - 声明式跳转:
<router-link to="/about">关于</router-link> - 支持对象写法:
router.push({ name: 'UserProfile', params: { id: '123' } })
外部跳转:不能用 router.push(),要用原生方式
以下任一方法都可打开新标签页或当前页跳转到外部 URL:
-
当前页跳转:
window.location.href = 'https://example.com' -
新标签页打开:
window.open('https://example.com', '_blank') -
带安全策略的新窗口(推荐):
window.open('https://example.com', '_blank', 'noopener,noreferrer')(防止新页面通过window.opener访问原页面) -
在模板中直接写链接:
<a href="https://example.com" target="_blank" rel="noopener noreferrer">访问官网</a>
常见误区与注意事项
这些写法看似能用,但实际有问题:
Vue 3 组合式 API 与 最佳实践,涵盖代码组织、useXxx 模式、组合式函数设计、Store 集成、响应式优化及功能抽取。
立即学习“前端免费学习笔记(深入)”;
- ❌
router.push('https://example.com')—— vue-router 会把它当作一个内部路径处理,最终跳转到/https://example.com,404 - ❌
<router-link to="https://example.com"></router-link>—— 同样被识别为相对路径,且不触发外部跳转 - ✅ 外链建议加
rel="noopener noreferrer",避免安全风险和性能影响 - ✅ 如果是用户生成内容中的外链,务必校验协议(只允许
http://和https://),防止javascript:注入
封装一个安全的外链跳转函数(可选)
便于复用和统一控制:
function openExternal(url) {
if (!url.startsWith('http://') && !url.startsWith('https://')) {
console.warn('非安全协议,拒绝跳转:', url)
return
}
window.open(url, '_blank', 'noopener,noreferrer')
}
调用:openExternal('https://vuejs.org')


















