1

There is a case where we used:

<template>
  <div id="app">
    <button @click="fetch">Fetch numbers</button>

    <div v-if="!getNumbers.length">Waiting for numbers...</div>

    <div v-if="getNumbers.length">
      <div v-for="number in getNumbers" :key="number.id">
        <h5>{{ number.owner }}</h5>
        <p>{{ number.phone }}</p>
      </div>
    </div>
  </div>
</template>

Is it a good practice? If not then how can be this improved?

8
  • 2
    I don't see why that will be a problem. The thing is, VueJS uses a virtual DOM so all the changes you make at runtime will be bunched/chunked together before writing it out to the actual DOM tree anyway :) the only thing is that you shouldn't use v-for and v-if together (which you're not doing anyway). The only optimization I would suggest is that you use <template> for the outer v-if, since you're using the div as simply a placeholder element. Commented Feb 25, 2020 at 15:05
  • 3
    What about changing the 2nd v-if to v-else? Commented Feb 25, 2020 at 15:06
  • 1
    Sure. Since you are checking against a boolean, then it makes sense to use v-else instead, but that shouldn't change the computational effort behind it. Commented Feb 25, 2020 at 15:08
  • I got confused by this part: The only optimization I would suggest is that you use <template> for the outer v-if since you're using the div as simply a placeholder element. Can you show it on code wht you mean? Commented Feb 25, 2020 at 15:12
  • 1
    Use <template v-if="getNumbers.length"> ... </template>, so you don't unnecessary produce a dummy <div> element. Or even better, just <template v-else> Commented Feb 25, 2020 at 15:13

1 Answer 1

1

Like you do it is OK. From style guide of vueJs : https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential

Sign up to request clarification or add additional context in comments.

Comments

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.