in Vue JS, I can do
<h1 v-if="someCondition">MY TITLE</h1>
Is there a way to base the element type on some condition?
For example, based on someCondition
I want my title to be <h1>
or <h2>
.
I suppose I could use
<template v-if="someCondition === 0">
<h1>MY TITLE</h1>
</template>
<template v-if="someCondition === 1">
<h2>MY TITLE</h2>
</template>
But is there a more straightforward way of writing this?
<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"
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
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With