VueJS HTML element type based on condition
This is where render
functions are useful. Whenever your template needs more advanced logic, render functions offer the use of Javascript with all of its logic flow capacity to generate the template, rather than HTML tags. You can read more about Vue's render functions here.
Here is a fiddle to demonstrate this example:
data() {
return {
someCondition: 1
}
},
render(h){
let tagType;
if (this.someCondition === 0) {
tagType = 'h1';
} else if(this.someCondition === 1) {
tagType = 'h2';
}
return h(tagType, null, 'MY TITLE');
}
If there is only 2 variations your best bet is to stick with v-if
and v-else
.
If there are more possible variations a dynamic component is the way to go (https://v2.vuejs.org/v2/guide/components-dynamic-async.html)
<component :is="dynamicComponent">Foo</component>
...
computed: {
dynamicComponent() {
return 'h'+this.i
}
}
Which will in turn render into <h1>
, <h2>
, <h{i}>
.
This is more useful though when switching between actual components, not the HTML h
tags.
https://codesandbox.io/s/vue-template-z40u7
<component :is="'h'+someCondition">MY TITLE</component>
your "someCondition" can be defined as props or data property and it can have a value from 1 to 6, in case you are going to use only "H tags"