Home > Software design >  How to access URL from a prop in a for loop in VueJS
How to access URL from a prop in a for loop in VueJS

Time:09-28

Having trouble figuring out how to access the url in my props to open them. Right now simply right clicking and opening in new tab works, but I'm trying to get them to open when clicked. How do I properly reference the href prop from the @click method?

<template>
  <div id="app">
    
    <div >
<a :href="link.href"  v-for="link in links" :key="link.href" @click="goTo">
      {{ link.name }}
    </a>
  </div>
    </div>


  </div>
</template>

<script>
export default {
  data() {
    return{
      links:[
 { name: 'Twitter', href: 'http://www.twitter.com' },
 { name: 'Github', href: 'http://www.github.com' },
]
    }
  },
  methods: {
    goTo() {
     window.open();
    }
  }
};
</script>```

CodePudding user response:

If you want to open a new window from the url, you can just pass the url as a parameter to the goTo function.

<template>
  <div id="app">
    
    <div >
<a href="javascript:void(0)"  v-for="link in links" :key="link.href" @click="goTo($event, link.href)">
      {{ link.name }}
    </a>
  </div>
    </div>


  </div>
</template>

<script>
export default {
  data() {
    return{
      links:[
 { name: 'Twitter', href: 'http://www.twitter.com' },
 { name: 'Github', href: 'http://www.github.com' },
]
    }
  },
  methods: {
    goTo(e, href) {
     e.preventDefault()
     window.open(href);
    }
  }
};
</script>

CodePudding user response:

You can do something like this :

<a href=""  v-for="link in links" :key="link.href" v-on:click.stop.prevent="goTo(link.href)">

Basically, click.stop.prevent will prevent the link from being clicked and redirected and will call the goTo function.

methods: {
  goTo(href) {
    window.open(href);
  }
}
  • Related