VueJS动态标签

时间:2018-07-23 09:42:12

标签: vue.js tabs vuejs2

在一件简单的事情上,我需要您的帮助。我看不到如何根据当前标签显示内容。

我很确定解决方案是如此接近,内容部分类似v-if

<button v-for="tab in tabs"
 v-bind:key="tab"
 v-bind:class="['tab-button', { active: currentTab === tab }]"
 v-on:click="currentTab = tab">
{{ tab }}
</button>

<div v-for="(fruit, fruit) in fruits" :key="fruit">
 <p>{{ fruit.name }}</p>
 <p >{{ fruit.price }}</p>
</div>

<div v-for="(vege, vege) in veges" :key="vege">
 <p>{{ vege.name }}</p>
 <p>{{ vege.price }}</p>
</div>

脚本部分

currentTab: 'fruits',
tabs: ['fruits', 'veges'],
fruits: [
 {
  name: 'fruit', price: '3$'
 }
],
veges: [
 {
  name: 'vege', price: '1$'
 }
 ]

3 个答案:

答案 0 :(得分:0)

是的,只需为每个标签内容添加v-if(添加包装器,因为v-for的优先级高于v-if,添加包装器)

 <button v-for="tab in tabs"
   v-bind:key="tab"
   v-bind:class="['tab-button', { active: currentTab === tab }]"
   v-on:click="currentTab = tab">
   {{ tab }}
 </button>
 <div v-if="currentTab === tabs[0]">
     <div v-for="(fruit, index) in fruits" :key="index">
      <p>{{ fruit.name }}</p>
      <p >{{ fruit.price }}</p>
     </div>
 </div>
 <div v-if="currentTab === tabs[1]">
     <div v-for="(vege, vege) in veges" :key="vege">
      <p>{{ vege.name }}</p>
      <p>{{ vege.price }}</p>
    </div>
 </div>

P.S。我建议使用对象而不是数组,以使用像这样的标签v-if="currentTab === tabs.fruits"

答案 1 :(得分:0)

尝试一下:

<div v-if="currentTab === 'fruits'" v-for="(fruit, fruit) in fruits" :key="fruit">
 <p>{{ fruit.name }}</p>
 <p >{{ fruit.price }}</p>
</div>

<div v-if="currentTab === 'veges'" v-for="(vege, vege) in veges" :key="vege">
 <p>{{ vege.name }}</p>
 <p>{{ vege.price }}</p>
</div>

答案 2 :(得分:0)

在模板内部使用v-if就像这样(如果您想根据Vue.js Docs切换多个元素)

 <template v-if="currentTab === 'fruits'">
    <div v-for="(fruit, index) in fruits" :key="index">
      <p>{{ fruit.name }}</p>
      <p >{{ fruit.price }}</p>
    </div>
 </template>
 <template v-else>
     <div v-for="(vege, index) in veges" :key="index">
       <p>{{ vege.name }}</p>
       <p>{{ vege.price }}</p>
     </div>
</template>