0

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?

1
  • 1
    Replace :click="window.location='buy_now_link'" by @click="window.location=product .buy_now_link". The colon is used to set a prop, the @ is used to add an event listener. Commented Oct 17, 2019 at 9:25

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.