MrUpsidown
MrUpsidown

Reputation: 22497

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?

Upvotes: 14

Views: 7773

Answers (3)

Dan
Dan

Reputation: 63099

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');
}

Upvotes: 2

TommyF
TommyF

Reputation: 7150

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

Upvotes: 4

Luigi
Luigi

Reputation: 314

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

Upvotes: 13

Related Questions