Vue.js按钮点击跳转URL失效问题求助及优化思路
Hey there! I see the problem with your code, and I've got two solid solutions for you—one that fixes your existing button setup, and another that uses a different tag approach like you're considering.
Solution 1: Fix the JavaScript in Your Button
The core issue here is that you’re using this.window instead of just window. window is a global browser object, so you don’t need to access it via this. Here’s the corrected version of your code:
<template> <button type="button" v-on:click="gotosite(modalDetails.final.product_url)">Buy</button> </template> <script> export default { // ... your other component options methods: { gotosite(producturl) { // Remove "this." before window to access the global object correctly window.location.href = producturl; } } } </script> <style></style>
Solution 2: Switch to an <a> Tag (Semantic & No JS Needed)
If you want to change the tag as you’re thinking, using an <a> tag styled like a button is a great choice—it’s more semantic for navigation and doesn’t require any JavaScript. Here’s how to implement it:
<template> <!-- Bind the href directly to your product URL --> <a :href="modalDetails.final.product_url" class="buy-button" target="_blank">Buy</a> </template> <script> // No need for the gotosite method anymore! export default { // ... your other component options } </script> <style> /* Style the link to match a button's appearance */ .buy-button { display: inline-block; padding: 8px 16px; background-color: #007bff; color: white; text-decoration: none; border-radius: 4px; border: none; cursor: pointer; } .buy-button:hover { background-color: #0056b3; } </style>
The target="_blank" attribute is optional—add it if you want the link to open in a new tab.
内容的提问来源于stack exchange,提问作者handsomer223

