我有一个Vue应用程序,我在数据元素中指定了所有链接,例如:
data(){
return{
products:[
{
Name: "Product 1",
buy_now_link: "https://www.product_1.com/",
},
{
Name: "Product 2",
buy_now_link: "https://www.product_2.com/",
}
]
}
}
上面的网址可能并不总是具有模式,它们可能有所不同。
在我的模板中,我有一个按钮,该按钮应将用户重定向到指定url中提供的链接。模板代码如下:
<div class="content">
<div class="nested" v-for="product in products">
<div class="one">
<button class="buy_now_button" :click="window.location='buy_now_link'">Buy now</button>
</div>
</div>
</div>
我收到错误Cannot set property 'location' of undefined
我该如何解决?
创建将用户重定向到链接的新方法。
Vue实例部分:
methods: {
redirectToLink(link) {
window.location = link;
}
}
并且在模板中:
<button class="buy_now_button" @click="redirectToLink(product.buy_now_link)">Buy now</button>
您可以按照以下方式进行此操作
<div class="content">
<div class="nested" v-for="product in products">
<div class="one">
<button class="buy_now_button" @click="redirectTo(product.buy_now_link)">Buy now</button>
</div>
data(){
return{
products:[
{
Name: "Product 1",
buy_now_link: "https://www.product_1.com/",
},
{
Name: "Product 2",
buy_now_link: "https://www.product_2.com/",
}
]
}
},
methods:{
redirectTo(url){
window.location=url
}
}