首页 > 解决方案 > 如何显示由一个模型中的另一个字段过滤的 2 个列表

问题描述

型号:文章。
ID。
姓名。类型:['代码','设计']

API获取所有文章

如何显示两个列表:
type ='Code'的
所有文章,type ='Design'的所有文章

换句话说,是否可以过滤 API 查询
或者在 API 端进行过滤更好?

额外:同上,但在嵌套环境中(即文章属于类别。如何在类别详细信息页面上进行操作。

标签: vue.jsvuejs3

解决方案


您可以使用计算属性。我构建了一个示例组件:

编辑:花了一些时间把它擦干。

父.vue

<template>
  <div class="parent">
    <div class="row">
      <div class="col-md-6">
        <article-list title="Code Articles" :articles="codeArticles" />
      </div>
      <div class="col-md-6">
        <article-list title="Design Articles" :articles="designArticles" />
      </div>
    </div>
  </div>
</template>

<script>
  import ArticleList from './ArticleList.vue'

  export default {
    components: {
      ArticleList
    },
    data() {
      return {
        articles: [
          {
            id: 1,
            name: 'Article1',
            type: 'Code'
          },
          {
            id: 2,
            name: 'Article2',
            type: 'Design'
          },
          {
            id: 3,
            name: 'Article3',
            type: 'Code'
          },
          {
            id: 4,
            name: 'Article4',
            type: 'Design'
          },
        ]
      }
    },
    computed: {
      codeArticles() {
        return this.articles.filter(article => article.type === 'Code');
      },
      designArticles() {
        return this.articles.filter(article => article.type === 'Design');
      }
    }
  }
</script>

文章列表.vue

<template>
  <div class="two-filtered-lists">
    <h5>{{ title }}</h5>
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>ID</th>
          <th>NAME</th>
          <th>TYPE</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="article in articles" :key="article.id">
          <td>{{ article.id }}</td>
          <td>{{ article.name }}</td>
          <td>{{ article.type }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
  export default {
    props: {
      title: {
        type: String,
        required: true
      },
      articles: {
        type: Array,
        required: true
      }
    }
  }
</script>

推荐阅读