Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js Giving a value to a href in a <a> tag

Sounds dumb but I can't find a way to pass a variable data defined in the href:

ComponentFile.vue I tried all of those:

<a href=" url ">{{ url }}</a>
<a href=" {{ url }}">{{ url }}</a>
<a href=" {{ url }}">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>
<a @click=" url " v-bind:href="url"> {{ url }}</a>


...
export default {
        data() {
                   url: 'http://anywhere.com'
  }
}

What is the correct way?

Thanks!

like image 725
commandantp Avatar asked Jan 17 '16 18:01

commandantp


People also ask

How do I pass a value from href to Vue?

To pass a value from Vue. js data to href, we can use template string literals. to set the href prop to /job/${r.id} where r is a reactive property.

How do you assign a value to a href?

The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!


2 Answers

You've defined data() as a function, but it isn't returning anything. It should return an object with the data like so:

export default {
    data() {
        return {
            url: 'http://anywhere.com'
        }
    }
}

Then either of these will work:

<a href="{{url}}">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>

EDIT FOR VUE 2:

Interpolating variables in attributes is no longer recommended. Change:

<a href="{{url}}">{{ url }}</a>

To one of these:

<a :href="url">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>
like image 143
Jeff Avatar answered Sep 21 '22 10:09

Jeff


realy simple:

<a :href="'mailto:' + email">{{email}}</a>
like image 29
Иван Гончаренко Avatar answered Sep 19 '22 10:09

Иван Гончаренко