AlyssaAlex
AlyssaAlex

Reputation: 716

Redirect on button click to a url specified in the data element in Vue

I have a Vue application, I am specifying all links in my data element like:

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/",
            }
        ]
    }
}

The urls above might not always have a pattern, they could be different.

In my template, I have a button that should redirect the user to the links provided in the specified urls. The template code is below:

<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>

I get an error Cannot set property 'location' of undefined

How can I solve this?

Upvotes: 0

Views: 1833

Answers (2)

Vibha Chosla
Vibha Chosla

Reputation: 713

You can do this like below

<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
 }
}

Upvotes: 0

Konrad Słotwiński
Konrad Słotwiński

Reputation: 699

Create new method that redirect user to link.

Vue instance part:

methods: {
  redirectToLink(link) {
    window.location = link;
  }
}

And in template:

<button class="buy_now_button" @click="redirectToLink(product.buy_now_link)">Buy now</button>

Upvotes: 2

Related Questions