首页 > vue.js 多维数组索引值的处理

vue.js 多维数组索引值的处理

1.数组结构如下

filters: [
    {
      categories: ['电子商务', '互联网医疗', '互联网金融'],
      showFilter: false,
      title: '分类'
    }, {
      categories: ['正在申购', '申购完成'],
      showFilter: false,
      title: '状态'
    }, {
      categories: ['杭州', '上海', '北京', '深圳', '广州'],
      showFilter: false,
      title: '地区'
    }
   ]

2.template如下

<div class="filter fl" track-by="$index" v-for="filter in filters">
    <div class="filter-title" @click="toggleFilter($index)">
      <h3>{{filter.title}}</h3>
    </div>
    <ul class="filter-list" transition="scaley" v-show="filter.showFilter">
      <li class="hairline-bottom" @click="changeFilter($index)" v-for="category in filter.categories">{{category}}</li>
    </ul>
</div>

3.我的需求:点击每个li的时候,让数组中每一个对象的title都变为对应的categories里面的文字

4.遇到的问题:两次v-for,在点击li的时候,$index是categories的索引,而非对象在filters中的索引,那么如何才能知道对象在filters中的索引,并且将对应的category值赋值到对应的对象的title上呢?比如:

this.filters[0].title = this.filters[0].categories[1]

5.简单的方法就是更改数据结构,几个大分类单独成为一个对象,但是感觉不太爽...


根据 文档,v-for 可以加入索引变量 ...

比如

<div v-for="(i, p) in items">
    <div v-for="(j, c) in p.child">
        {{i}}, {{j}}
    </div>
</div>

這種巢狀的 v-for 可以用 $parent.$index 來取得上層的 $index

<div class="filter fl" track-by="$index" v-for="filter in filters">
    <div class="filter-title" @click="toggleFilter($index)">
      <h3>{{filter.title}}</h3>
    </div>
    <ul class="filter-list" transition="scaley" v-show="filter.showFilter">
      <li class="hairline-bottom" @click="changeFilter($parent.$index, category)" v-for="category in filter.categories">{{category}}</li>
    </ul>
</div>
data: {
    filters: [
    {
      categories: ['电子商务', '互联网医疗', '互联网金融'],
      showFilter: true,
      title: '分类'
    }, {
      categories: ['正在申购', '申购完成'],
      showFilter: false,
      title: '状态'
    }, {
      categories: ['杭州', '上海', '北京', '深圳', '广州'],
      showFilter: false,
      title: '地区'
    }
   ]
    },
methods: {
    toggleFilter(index) {
        this.filters[index].showFilter = this.filters[index].showFilter ? false : true
    },
    
    changeFilter(index, category) {
        this.filters[index].title = category
    }
}

完整實現

jsFiddle

補充評論的 v-for 為何可以使用 $parent

https://github.com/vuejs/vue/blob/dev/src/directives/public/for.js

    var parentScope = this._scope || this.vm
    var scope = Object.create(parentScope)
    // ref holder for the scope
    scope.$refs = Object.create(parentScope.$refs)
    scope.$els = Object.create(parentScope.$els)
    // make sure point $parent to parent scope
    scope.$parent = parentScope // <- Here

這是源碼,可以看到在處理 v-for 時,會指定 parentScope 給當前 scope.$parent ,這就是可以用的原因 :)

【热门文章】
【热门文章】