0

A simple question in Vue.js. In this code, the second "project" don't have any "Property", obviously no "Number", this make the html shows blank, how to handle this when there's no data in the array? I've tried v-if but can't make it work. Thanks

<div v-for="propiedad in info" class="propiedad">
   <div class="propiedad">
       {{ project.Property[0].Number }}
   </div>
</div>
1
  • What v-if did you try? Where does project come from and what sort of data is in it? What does it have to do with info or propiedad? Commented Jul 21, 2020 at 0:52

2 Answers 2

2

I take the question "this make the HTML shows blank" as "There is some errors in the console and the entire page fails."

You can do it by project && project.Property[0] && project.Property[0].Number

Or if you are working with babel with plugin babel-preset-env, you can take advantage of the optional chaining feature

project?.Property[0]?.Number

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

Comments

0

First, this looks off because of the loop that you are not using. (Is there a mistake or why bother showing it?)

A v-if should work, but it often gets verbose.

<div class="propiedad" v-if="project.Property && project.Property.length > 0 && project.Property[0].Number>

That should cover all the bases.

Therefore it's often cleaner to massage the data beforehand. Maybe make all projects have defaults.project.Property, so you don't have to check if it exists.

Or just make computed properties so your template can look nice

computed: {
     hasProperty(){
        return this.project.Property 
          && this.project.Property.length > 0 
          && this.project.Property[0].Number
     }
}

<div class="propiedad" v-if="hasProperty"> ... </div>

Or if this is indeed related to the loop . Make a computed array that filters the array.

computed: {
   // Here I make the wild assumption that info are actually projects
   // (just to make the loop relevant)
   filtered(){
     // Skip all the projects without "Properties".
     return this.info.filter( i => i.Property.length > 0 )
   }
}

<div v-for="propiedad in filtered"> .... 

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.