vuejs v-仅基于类别

时间:2018-01-31 10:31:16

标签: vue.js

我有一系列元素,我在页面上显示,使用v-for:

<template>
  <v-container>
     <v-layout  row wrap v-for="offer in offers.slice((current_page-1)*5, current_page*5)">
        ...
    </v-layout>
  <v-container>
</template>

<script>
   export default{
      data(){
        offers: [array of offers here],
      }
   }

现在我决定添加类别并仅显示来自数组的某些类别的商品(数据类似于:offer.speciality[1] - 类别1; offer.speciality[2] - 类别2等...)

所以我添加了最简单的v-show元素,如下所示:

<v-layout  row wrap v-for="offer in offers.slice((current_page-1)*5, current_page*5)" 
v-show="checkArray(offer, speciality)">

和专业变量(从选择中获取值)

<script>
   export default{
      data(){
        offers: [array of offers here],
        speciality:''
      }
   }

其中函数checkArray只是检查specialityID是否与offer.speciality [i]相同并返回true或false到v-show元素

    checkArray(offer, id){
        if (id)
        {
            for (var i in offer.specialities) {
                if (offer.specialities[i] == id)
                {
                  return true;
                  break;
                } 
            }
            return false;
        }
        else {
            return true;
        }
    },

一切正常,但是在这一点上,正如我们所知,v-show功能显示了一些优惠,同时隐藏了其余部分,而不是将其从正在进行分页的DOM中删除(每页五个优惠)无法配置,示例

显示特色1 - &gt;的优惠; HTML

offer.speciality[1]
offer.speciality[1]
offer.speciality[2] (display:none;)
offer.speciality[3] (display:none;)
offer.speciality[] (display:none;)
Pagination (1) 2 3 4 ...

那么我应该采用什么方法来代替od v-show来实现这项工作?我应该删除v-show=""并在v-for内设置某种条件吗?如何使这种动态变为动态,而v-for是懒惰的,并且我触发了speciality变量从选择中的变化?

1 个答案:

答案 0 :(得分:1)

我认为您应该对过滤车辆使用计算属性,这是

的示例

new Vue({
	el:"#app",
  data:{
  	manufacturer:'',
    cars: [
    				{manufacturer:"toyota", model:2012},
            {manufacturer:"ford", model:2013},
            {manufacturer:"subaro", model:2010},
            {manufacturer:"ford", model:2014},
            {manufacturer:"subaro", model:2010},
            {manufacturer:"ford", model:2016},
            {manufacturer:"dodge", model:2014},
            {manufacturer:"ford", model:2015},
            {manufacturer:"ford", model:2014}
            
          ],
    current_page:1
  },
  computed:{
  	filteredCars: function(){
    	var cars = []
    	if(this.manufacturer == ''){
      	cars = this.cars
      }
      else
      {
        cars = this.cars.filter(car => {
          if (car.manufacturer == this.manufacturer){
            return true
          }
          return false
        })
      }
      return cars.slice((this.current_page-1)*3, this.current_page*3)
    }
  }

})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
  <label for="">Type manufacturer</label>
  <input type="text" v-model="manufacturer">
  <hr>
  <ul>
    <li v-for="car in filteredCars">{{car.manufacturer}} | {{car.model}}</li>
  </ul>
  
  <hr>
  <label for="">Page</label>
  <input type="number" v-model.number="current_page">
</div>