Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS HTML element type based on condition

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?

like image 862
MrUpsidown Avatar asked May 17 '19 13:05

MrUpsidown


3 Answers

<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"

like image 138
Luigi Avatar answered Oct 31 '22 12:10

Luigi


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

like image 3
TommyF Avatar answered Oct 31 '22 14:10

TommyF


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');
}
like image 1
Dan Avatar answered Oct 31 '22 14:10

Dan