简体   繁体   中英

How to access URL from a prop in a for loop in VueJS

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 class="container">
<a :href="link.href" class="link" 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>```

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 class="container">
<a href="javascript:void(0)" class="link" 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>

You can do something like this :

<a href="" class="link" 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM