Reputation: 8770
Is it possible to bind an HTML tag (element) to the value of a data or property in Vue 2?
I tried different syntaxes but couldn't get any to work, and googling didn't help.
Here are two of the syntaxes I tried:
Direct 'string' interpolation:
<{{ someProp ? 'button' : 'a' }}>
<!-- Some complex template I want to keep DRY -->
</{{ someProp ? 'button' : 'a' }}>
v-bind the tag on a template element (hopeful guess):
<template :tag="someProp ? 'button' : 'a'">
<!-- Some complex template I want to keep DRY -->
</template >
If that's not possible, how can I avoid duplicating the content and attributes of the element just to change the associated HTML tag? What I want to avoid is:
<button v-if="someProp" /* Some attribute bindings */>
<!-- Some complex template I want to keep DRY -->
</button>
<a v-else /* Repeating the above attribute bindings */>
<!-- Repeating the above template, breaking the DRY principle -->
</a>
Upvotes: 0
Views: 2545
Reputation: 82439
The dynamic component tag in Vue is intended to work with Vue components, but it does work with HTML tags as well.
<component :is="tag">Click me</component>
Here is an example.
console.clear()
new Vue({
el:"#app",
data:{
tag: "a",
},
methods:{
onClick(){
alert('clicked')
},
changeTag(){
this.tag = this.tag == "a" ? "button" : "a"
}
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<component :is="tag" @click="onClick" href="javascript:void(0)">Click me</component>
<hr>
<button @click="changeTag">Change tag</button>
</div>
Upvotes: 3