0

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>
2
  • Simply use: <Table1 v-if="flag1" /> <Table2 v-if="flag2" /> <Table3 v-if="flag3" /> you can also use v-if-else. check documentation: vuejs.org/guide/essentials/conditional#v-else-if Commented Dec 13, 2024 at 11:34
  • you can accept an answer (the gray checkbox) btw, even better than upvoting Commented Dec 14, 2024 at 19:06

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

@Khan If your intent is to display one table at a time, this is the correct answer
I certainly advice to use a component-based method: it can be nicely adopted for any scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.