I’m building a Vue.js application that requires conditional rendering of multiple tables based on certain conditions. I have a set of flags that determine which tables should be rendered, and I’m struggling to find a clean and efficient way to implement this.
<Table1 v-if="flag1 && !flag2 && !flag3" />
<Table2 v-if="flag2 && !flag1 && !flag3" />
<Table3 v-if="flag3 && !flag1 && !flag2" />
As you can see, this approach is repetitive and error-prone. I’m looking for a way to simplify this code and make it more maintainable.
Using a single v-if statement with multiple conditions
Creating a separate component for each table
Using a mixin to handle the conditional rendering
What i want is
A clean and efficient way to conditionally render multiple tables based on a set of flags
A solution that is easy to maintain and extend
<template>
<div>
<Table1 v-if="flag1 && !flag2 && !flag3" />
<Table2 v-if="flag2 && !flag1 && !flag3" />
<Table3 v-if="flag3 && !flag1 && !flag2" />
</div>
</template>
<script>
export default {
data() {
return {
flag1: true,
flag2: false,
flag3: false
}
}
}
</script>
Khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The problem that you don’t render multiple tables, you render only one at a time. For that you need a state variable instead of multiple booleans (you can name your variable as you like):
<template>
<div>
<Table1 v-if="tableNum === 1" />
<Table2 v-if="tableNum === 2" />
<Table3 v-if="tableNum === 3" />
</div>
</template>
<script>
export default {
data() {
return {
tableNum: 1
}
}
}
</script>
Another option is to use component
:
<template>
<div>
<Component :is="[Table1, Table2, Table3][tableNum -1]" />
</div>
</template>
<script>
export default {
data() {
return {
tableNum: 1
}
}
}
</script>
2