Vue.js 2.6能否同时用:to跳转组件与:href打开外部网页?
解决Vue Router侧边栏菜单项同时渲染组件并打开外部网页的问题
直接绑定:to和:href会导致Vue Router优先处理外部链接跳转,无法同时实现两个需求。可以通过手动触发两个独立行为来解决:
实现步骤
- 移除
v-list-item上的:to和:href属性 - 添加点击事件处理函数,分别触发路由跳转和外部链接打开
Vue 2 代码示例
<template> <v-list-item @click="handleMenuClick"> <v-list-item-title>universal</v-list-item-title> </v-list-item> </template> <script> export default { methods: { handleMenuClick() { // 当前页面跳转路由,渲染目标组件 this.$router.push('/universal'); // 新窗口打开外部网页 window.open('https://google.com', '_blank'); } } } </script>
Vue 3 代码示例(Composition API)
<template> <v-list-item @click="handleMenuClick"> <v-list-item-title>universal</v-list-item-title> </v-list-item> </template> <script setup> import { useRouter } from 'vue-router'; const router = useRouter(); const handleMenuClick = () => { router.push('/universal'); window.open('https://google.com', '_blank'); }; </script>
注意事项
- 浏览器可能会拦截
window.open的弹窗,建议提前提示用户允许弹窗权限 - 确保路由路径
/universal已在Vue Router中正确配置对应组件
内容的提问来源于stack exchange,提问作者Maykel
相关产品推荐
相关产品推荐

