10

Pretty simple question.

In my vue.js template I have:

<template v-for="node in nodes">
  [[ node ]]
</template>

I want to return nodes in the list or print "N/A" if the list is empty.

I know how to do this with a js function, but not sure how to accomplish the same thing from within the template.

1
  • you mean you want to check if nodes list is empty ? Commented Jun 5, 2019 at 5:30

4 Answers 4

13

You should check for both undefined and length using Vue's v-if. If you ever use asyncComputed for example, it will be undefined until the async method resolves. So you are covered for nodes=null, nodes=undefined, and nodes=[].

<template v-if="!nodes">
  Loading
</template>
<template v-else-if="!nodes.length">
  Empty
</template>
<template v-else v-for="node in nodes">
  {{ node }}
</template>

Or combine them

<template v-if="!nodes || !nodes.length">
  Nothing To Show
</template>
<template v-else v-for="node in nodes">
  {{ node }}
</template>

I like using !nodes.length instead of length !== 0 just in case something unexpected besides an array ends up in the data, in which case it will most likely use the empty template and not throw an exception. Less typing too!

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

Comments

3

You can check like:

<template v-if="nodes.length">  // When there are some records available in nodes
  // Iterate it and display the data
</template >
<template v-else>
  // No record found
</template>

Reference

Comments

0

Use render function like

export default {
  data() {
    return {
      nodes: ['item 1', 'item 2']
    }
  },
  render(h) {
    if (this.nodes.length == 0) {
      return h('p', 'No item')
    } else {
      return h(
        'p',
        {},
        this.nodes.map((item) => h('p', item))
      )
    }
  }
}

Comments

0

to check if a list is empty, you just need to use v-if, in that way your template will be like below :

<template v-if="nodes.length === 0">
  N/A
</template>

<template v-for="node in nodes"  v-else>
  [[ node ]]
</template>

for more information about Conditional Rendering VueJs please check the doc.

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.