I want to implement a cleaner version of the following code snippet:
<div v-for="section in sections">
<h1 v-if="section.level === 1">
...
</h1>
<h2 v-else-if="section.level === 2">
...
</h2>
<h3 v-else-if="section.level === 3">
...
</h3>
<h4 v-else-if="section.level === 4">
...
</h4>
<h5 v-else-if="section.level === 5">
...
</h5>
<h6 v-else-if="section.level === 6">
...
</h6>
</div>
Instead of having logic in the template, I would like to abstract it into functions. Here is an example:
<div v-for="section in sections">
<h1 v-if="isLevel(section, 1)">
...
</h1>
<h2 v-else-if="isLevel(section, 2)">
...
</h2>
<h3 v-else-if="isLevel(section, 3)">
...
</h3>
<h4 v-else-if="isLevel(section, 4)">
...
</h4>
<h5 v-else-if="isLevel(section, 5)">
...
</h5>
<h6 v-else-if="isLevel(section, 6)">
...
</h6>
</div>
I am new to Vue.js and looking for the best way to achieve this. One approach I can think of is creating custom components for each heading level (pseudo code):
<div v-for="section in sections">
<MyHeader section="{{ section }}" />
</div>
new Vue({
template: the MyHeader one,
props: {
section: true
},
methods: {
isLevel1: function() {
return this.$data.section.level === 1
},
isLevel2: function() {
return this.$data.section.level === 2
},
...
}
})
<template name="MyHeader">
<h1 v-if="isLevel1">
...
</h1>
<h2 v-else-if="isLevel2">
...
</h2>
<h3 v-else-if="isLevel3">
...
</h3>
<h4 v-else-if="isLevel4">
...
</h4>
<h5 v-else-if="isLevel5">
...
</h5>
<h6 v-else-if="isLevel6">
...
</h6>
</template>
While this approach works, I find it cumbersome to create custom components for each heading level. I want to explore the idiomatic way of handling this in Vue.js without directly using the render
function. Any insights or suggestions would be appreciated!