VueJs v-for how to check list undefined before continue
Asked Answered
A

1

11

Refer to the template below, how to add condition to make sure the menu is not undefined inside the v-for attribute?

I've tried v-for="menu?item in menu.items:[]" and v-for="item in menu?.items" but neither works.

<div v-for="item in menu.items">{{item.text}}</div>
Afterbrain answered 2/5, 2017 at 14:44 Comment(0)
C
16

Put the div with the v-for directive within a <template> that checks for menu via v-if:

<template v-if="menu">
  <div v-for="item in menu.items">{{ item.text }}</div>
</template>

This way, the div inside the template won't be rendered if menu does not exist.


If you really want the check within the v-for statement, like you are attempting, it would look like this:

<div v-for="item in (menu ? menu.items : [])">{{ item.text }}</div>
Caplin answered 2/5, 2017 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.