如何将类别ID传递到带有vue的产品列表?

时间:2018-01-20 13:59:55

标签: javascript html css vue.js vuejs2

点击类别后,您会获得category_id,传递到产品列表,并按类别显示产品?转到jsfiddle

如何实现呢?如下图所示:

此Apple类别:

enter image description here

这个小米类:

enter image description here

查看javascropt文件:

var vm = new Vue({
  el: '#app',
  data: {
    active: 0,
    category: [{
      category_id: "1",
      category_name: "Apple"
    }, {
      categoryid: "2",
      category_name: "Xiaomi"
    }],
    products: [

      {
        category_id: "1",
        goods_name: "iphone6s",
      }, {
        category_id: "1",
        goods_name: "macbook pro"
      }, {
        category_id: "2",
        goods_name: "hongmi5 Plus"
      }
    ]
  },
  methods: {
    toggle(i, v) {
      this.active = i
      this.currentView = v
    }
  }


})

CSS文件:

.active {
  color: red;
  border-bottom: 1px solid red;
}

ul li {
  padding: 0 15px;
  float: left;
  list-style: none;
}

HTML文件:

<div id="app">

  <ul>
    <li @click="toggle($index,item.category_name)" v-for="item in category" :class="{active: active == $index}">{{ item.category_name }}</li>
  </ul>
  <br>
  <div class="layui-tab-content">
    <div class="layui-tab-item" v-for="item in products"> {{item.goods_name}}</div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您需要一个计算的categoryProducts,按category_id筛选products数组,请参阅jsfiddle

var vm = new Vue({
  el: '#app',
  data: {
    currentView: 'child1',
    active: '1',
    category: [{
      category_id: "1",
      category_name: "Apple"
    }, {
      category_id: "2",
      category_name: "Xiaomi"
    }],
    products: [
      {
        category_id: "1",
        goods_name: "iphone6s",
      }, {
        category_id: "1",
        goods_name: "macbook pro"
      }, {
        category_id: "2",
        goods_name: "hongmi5 Plus"
      }
    ]
  },
  computed: {
    categoryProducts () {
        let that = this
        return this.products.filter(p => p.category_id === that.active)
    }
  },
  methods: {
    toggle(i, v) {
      this.active = i
      console.log(i)
      //this.currentView = v
    }
  }


})