渲染后过滤2种不同的成分

时间:2019-04-29 16:20:31

标签: vue.js

我遇到了这个问题:我正在尝试订购2个同级组件,它们都有自己的数据和自己的属性。但是这两个不同的数据具有相同的“位置”属性。

数据库结构

章节

chapterId

title (string)

position (integer)

页面

pageId

name (string)

position (integer)

body (text)

这是我的 Summary.vue

<template>

  <div>

   <summary-chapter v-for="chapter in data.chapters" :chapter="chapter"></summary-chapter>

   <summary-page v-for="page in data.pages" :page="page"></summary-page>

  </div>

</template>

数据变量为:

data : 
{
   'chapters' : { {chapterId: 1, ...}, {chapterId: 2, ...}, {chapterId: 3, ...}, ... },
   'pages' : { {pageId: 1, ...}, {pageId: 2, ...}, {pageId: 3, ...}, ... }
}

我正在寻找这种结果:混合

Pos: 1 - Page with id of 12

Pos: 2 - Chapter with id of 7

Pos: 3 - Chapter with id of 2

Pos: 4 - Page with id of 4

Pos: 5 - Page with id of 13

Pos: 6 - Chapter with id of 1

但是我总是第一章,然后是所有页面:

Pos: 2 - Chapter with id of 7

Pos: 3 - Chapter with id of 2

Pos: 6 - Chapter with id of 1

Pos: 1 - Page with id of 12

Pos: 4 - Page with id of 4

Pos: 5 - Page with id of 13

我真的不知道如何正确地做。 我试图过滤计算的数据属性 我尝试dto构建父组件摘要行,根据类型,该组件包含章组件 page组件 我尝试了100种其他方式...:(

你们有小费吗?

提前感谢您的时间。

路易

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是合并这两个数组,然后按其位置排序:

null

然后在您的模板中按以下类型呈现它:

computed: {
  sortedItems () {
    let chapters = this.chapters.map(chapter => ({ ...chapter, type: 'chapter' }))
    let pages = this.pages.map(page => ({ ...page, type: 'page' }))
    return []
      .concat(chapters)
      .concat(pages)
      .sort((a, b) => (a.position - b.position))
  }
}