Ad

Vue.js Giving A Value To A Href In A Tag

- 1 answer

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 target="_blank" rel="nofollow noreferrer" href=" url ">{{ url }}</a>
<a target="_blank" rel="nofollow noreferrer" href=" {{ url }}">{{ url }}</a>
<a target="_blank" rel="nofollow noreferrer" href=" {{ url }}">{{ url }}</a>
<a v-bind:target="_blank" rel="nofollow noreferrer" href="url">{{ url }}</a>
<a @click=" url " v-bind:target="_blank" rel="nofollow noreferrer" href="url"> {{ url }}</a>


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

What is the correct way?

Thanks!

Ad

Answer

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 target="_blank" rel="nofollow noreferrer" href="{{url}}">{{ url }}</a>
<a v-bind:target="_blank" rel="nofollow noreferrer" href="url">{{ url }}</a>

EDIT FOR VUE 2:

Interpolating variables in attributes is no longer recommended. Change:

<a target="_blank" rel="nofollow noreferrer" href="{{url}}">{{ url }}</a>

To one of these:

<a :target="_blank" rel="nofollow noreferrer" href="url">{{ url }}</a>
<a v-bind:target="_blank" rel="nofollow noreferrer" href="url">{{ url }}</a>
Ad
source: stackoverflow.com
Ad