VueJS 2.6中编程式路由与“在新标签页打开链接”功能实现
Great question! The issue here is that when you use @click with this.$router.push(), you’re relying purely on JavaScript to trigger navigation—there’s no native <a> tag involved, so the browser doesn’t show its default right-click menu options for opening links in new tabs or windows.
The good news is you can replicate the behavior of the <v-btn :to> component while keeping programmatic control, by leaning into native browser behavior with a properly configured <a> tag (Vuetify’s v-btn lets you change its rendered tag type easily).
Approach 1: Use v-btn as an <a> Tag with Resolved Route URL
This method directly turns your button into a native link, giving the browser all the cues it needs for right-click options, while still using Vue Router for single-page navigation on left-click.
<template> <v-btn tag="a" :href="targetRouteUrl" @click.prevent="goto" > GO </v-btn> </template> <script> export default { computed: { targetRouteUrl() { // Resolve the named route to its full, browser-friendly URL return this.$router.resolve({ name: 'route-name' }).href } }, methods: { goto() { // Add your custom pre-navigation logic here (if needed) // Example: Validate form data, log analytics, etc. // Trigger single-page navigation without page reload this.$router.push({ name: 'route-name' }) } } } </script>
Why this works:
- The
<a>tag with a validhreftells the browser to display its standard right-click menu (including "Open in new tab"). @click.preventstops the browser from doing a full page reload when left-clicked, so$router.push()handles smooth single-page navigation.- You retain full control to add custom logic in the
goto()method before navigating.
Approach 2: Wrap v-btn in <router-link>
If you prefer to use Vue Router’s built-in <router-link> component, you can leverage its scoped slot to add custom logic while keeping the native link behavior.
<template> <router-link :to="{ name: 'route-name' }" custom v-slot="{ navigate }" > <v-btn @click="handleClick(navigate)">GO</v-btn> </router-link> </template> <script> export default { methods: { handleClick(navigate) { // Add your custom pre-navigation logic here // ... // Trigger the router-link's native navigation behavior navigate() } } } </script>
Why this works:
<router-link>renders as a native<a>tag by default, so right-click menu options are available.- The
customprop and scoped slot let you take over the click handler, run your own logic, then call the built-innavigate()function for single-page routing.
内容的提问来源于stack exchange,提问作者Francois

