VueJs v-for how to check list undefined before continue

mind1n picture mind1n · May 2, 2017 · Viewed 14.4k times · Source

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>

Answer

thanksd picture thanksd · May 2, 2017

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>