vue.js:loop + component + if / else?

时间:2018-03-25 17:59:32

标签: vue.js vuejs2 vue-component

我有以下

<tabs>
    //If tab.name is not null
    <tab v-for="tab in tabs" :key="tab.id" :name="tab.name" :suffix="tab.id">
    </tab>
    //If tab.name is null
    <tab v-for="tab in tabs" :key="tab.id" :name="tab.id">
    </tab>
</tabs>

我想为我的数据运行一个循环,并根据我的条件不同地渲染组件。

我不能为我的生活弄清楚如何做到这一点。 v-else需要另一个元素声明,但是如果你同时放入v-for它将只运行循环两次。我试过this,但它似乎不适用于我的情况。如果我<template :name="tab.name">该组件表示它缺少必需的属性name

这应该如何在vue中起作用?

2 个答案:

答案 0 :(得分:1)

You can use v-for on a <template> element and use v-if inside:

<tabs>
    <template v-for="tab in tabs">
        <!-- //If tab.name is not null -->
        <tab v-if="tab.name" :key="tab.id" :name="tab.name" :suffix="tab.id">
        </tab>
        <!-- //If tab.name is null -->
        <tab v-else          :key="tab.id" :name="tab.id">
        </tab>
    </template>
</tabs>

Demo:

Vue.component('tab', {
  props: ['name', 'suffix'],
  template: `<div>tab - name: {{ name }} - suffix: {{ suffix || 'not available' }}</div>`
});
Vue.component('tabs', {
  props: ['tabs'],
  template: `<div>tabs<hr><slot :tabs="tabs"></slot></div>`
});
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    tabs: [{id: 1, name: "Alice"}, {id: 2}]
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <tabs :tabs="tabs">
    <template v-for="tab in tabs">
      <!-- //If tab.name is not null -->
      <tab v-if="tab.name" :key="tab.id" :name="tab.name" :suffix="tab.id"></tab>
      <!-- //If tab.name is null -->
      <tab v-else          :key="tab.id" :name="tab.id"></tab>
    </template>
  </tabs>
</div>

答案 1 :(得分:0)

你可以试试这个

<tabs>
    //If tab.name is not null
   <tab v-for="tab in tabs" :key="tab.id" :name="tab.name" :suffix="tab.id">
        <template v-if="tab.name != null">
           // conditional if code
        </template>
        <template v-else>
           // conditional else code
        </template>
   </tab>
</tabs>