如果值为 null,则跳过对象项

新手上路,请多包涵

我在 vue js 中有一个嵌套的 for ... in 循环。如果元素的值为 null ,我想要跳过元素。这是html代码:

 <ul>
    <li v-for="item in items" track-by="id">
        <ol>
            <li v-for="child in item.children" track-by="id"></li>
        </ol>
    </li>
</ul>

null 元素可能同时存在于 itemitem.children 对象中。

例如:

 var data = {
   1: {
      id: 1,
      title: "This should be rendered",
      children: {
          100: {
              id: 100,
              subtitle: "I am a child"
          },
          101: null
      }
   },
   2: null,
   3: {
       id: 3,
       title: "Should should be rendered as well",
       children: {}
   }
};

使用此数据 data[1].children[101] 不应呈现,如果 data[1].children[100] 稍后变为空,则应将其从列表中省略。

PS 我知道这可能不是表示数据的最佳方式,但我对此不承担任何责任:)

原文由 King Julien 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 710
1 个回答

编辑:实际上,一个简单的 v-if 可能会起作用:

 <li v-for="item in items" v-if="item !== null" track-by="id">

试试看。如果没有,请执行以下操作:

您可以为此添加过滤器(在 App 实例之前的 main.js 中):

 Vue.filter('removeNullProps',function(object) {
  // sorry for using lodash and ES2015 arrow functions :-P
  return _.reject(object, (value) => value === null)
})

然后在模板中:

 <li v-for="item in items | removeNullProps" track-by="id">
    <ol>
        <li v-for="child in item.children | removeNullProps" track-by="id"></li>
    </ol>
</li>

原文由 Linus Borg 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题