Reputation: 133
So, I'm trying to create a dynamic href in a Vue component that can be edited in the App.vue file (without having to edit it in the component file).
Just like the name1, name2, name3 and name4 you can see in the file
<div class="navigationdrawer">
<div id="mySidenav" class="sidenav">
<a href="#">{{ name1 }}</a>
<a href="#">{{ name2 }}</a>
<a href="#">{{ name3 }}</a>
<a href="#">{{ name4 }}</a>
</div>
</div>
<script>
export default {
name: 'NavigationDrawer',
props: {
msg: String,
name1: String,
name2: String,
name3: String,
name4: String,
link1: String,
link2: String,
link3: String,
link4: String
}
</script>
When I put <a href= {{ link1 }}>{{ name1 }}</a>
It works with {{ name1 }} but the {{ link1 }} part gives an error.
Upvotes: 7
Views: 12457
Reputation: 1255
Can you be more specific about what level of dynamics in populating 'href' attribute are you looking for?
Just following the #TheGuardian answer, consider redesigning your module with the template like in the example below:
<div class="navigationdrawer">
<div id="mySidenav" class="sidenav">
<a :href="link.href" v-for="link in hyperlinks" :key="link.href">
{{ link.display }}
</a>
</div>
Model:
<script>
export default {
name: 'NavigationDrawer',
props: {
msg: String,
hyperlinks: [
{
display: String,
href: String
},
{
display: String,
href: String
}
]
}
This way the 'href' attribute stays bound together with the display text. This way, many hyperlink nodes can be added dynamically into the HTML DOM tree.
You can also concatenate the 'href' attribute value in the HTML Node like in this example below:
<div class="navigationdrawer">
<div id="mySidenav" class="sidenav">
<a :href="'https://myDomainName/'+link.href" v-for="link in hyperlinks" :key="link.href">
{{ link.display }}
</a>
</div>
This way, the 'href' attribute value can be populated semi-dynamically.
Hope this helps.
Upvotes: 1
Reputation: 324
Mustaches cannot be used inside HTML attributes. Instead, use a v-bind directive:
<a v-bind:href="link1">{{ name1 }}</a>
or with shorthand
<a :href="link1">{{ name1 }}</a>
Also, I would suggest to use an array of links to make the component more dynamic.
<div class="navigationdrawer">
<div id="mySidenav" class="sidenav">
<a :href="link.href" v-for="link in links" :key="link.href">
{{ link.name }}
</a>
</div>
</div>
links:
[
{ name: 'Name 1', href: 'http://name1.com' },
{ name: 'Name 2', href: 'http://name2.com' },
]
Upvotes: 10