Bootstrap-Vue:如何使用Table组件的复选框来过滤数据?

Bootstrap-Vue: How to use checkboxes with Table component to filter data?

我正在使用 Bootstrap-Vue's TABLE 组件来显示数据。工作正常。

但是,我不知道如何使用复选框来切换 on/off 某些数据项。例如,如果用户选中 "open" 框,table 将更新并仅显示状态为 "open" 的项目。

谁能帮我解决这个问题?

这是我的演示代码:link to live sandbox code

<template>
  <div>
    <b-form-group label>
      <b-input-group>
        <b-form-input v-model="filter" placeholder="Type to search for a specific issue"></b-form-input>
        <b-input-group-append>
          <b-button :disabled="!filter" @click="filter = ''">Clear</b-button>
        </b-input-group-append>
      </b-input-group>
    </b-form-group>
    <b-form-group label="View Status:">
      <b-form-checkbox-group
        id="checkbox-group-1"
        v-model="selected"
        :options="options"
        name="flavour-1"
      ></b-form-checkbox-group>
    </b-form-group>
    <b-table :items="posts" :fields="fields" :filter="filter">
      <!-- A custom formatted column -->
      <template slot="name" slot-scope="data">{{ data.value.user }}</template>
    </b-table>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      filter: null,
      selected: ["pending"], // Must be an array reference!
      options: [
        { text: "Open", value: "open" },
        { text: "Assigned", value: "assigned" },
        { text: "Pending", value: "pending" },
        { text: "Closed", value: "closed" }
      ],
      rawPosts: [
        {
          userId: 1,
          status: "open",
          id: 1,
          title:
            "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
          body:
            "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        },
        {
          userId: 1,
          status: "open",
          id: 2,
          title: "qui est esse",
          body:
            "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
        },
        {
          userId: 1,
          status: "closed",
          id: 3,
          title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
          body:
            "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
        },
        {
          userId: 1,
          status: "assigned",
          id: 4,
          title: "eum et est occaecati",
          body:
            "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
        },
        {
          userId: 1,
          status: "pending",
          id: 5,
          title: "nesciunt quas odio",
          body:
            "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
        }
      ],
      users: [
        {
          uid: 1,
          firstname: "Claiborne",
          lastname: "Heberden",
          email: "cheberden0@gravatar.com"
        },
        {
          uid: 2,
          firstname: "Gerick",
          lastname: "Tetla",
          email: "gtetla1@whitehouse.gov"
        },
        {
          uid: 3,
          firstname: "Raymund",
          lastname: "Espy",
          email: "respy2@freewebs.com"
        },
        {
          uid: 4,
          firstname: "Dilly",
          lastname: "Dimitriev",
          email: "ddimitriev3@skype.com"
        },
        {
          uid: 5,
          firstname: "Roby",
          lastname: "Tabner",
          email: "rtabner4@sohu.com"
        }
      ],
      fields: [
        { key: "id" },
        { key: "title" },
        { key: "body" },
        { key: "user", label: "Assigned To" }
      ]
    };
  },
  created() {
    //this.loadPosts();
    //this.loadNames();
  },
  methods: {
    userFrom(id) {
      const user = this.users.find(user => user.uid === id);
      return user ? `${user.lastname}, ${user.firstname}` : "not assigned";
    }
  },
  computed: {
    posts() {
      if (this.rawPosts.length && this.users.length) {
        return this.rawPosts.map(rawPost => ({
          ...rawPost,
          user: this.userFrom(rawPost.userId)
        }));
      } else {
        console.log("some not assigned");
      }
    }
  }
};
</script>

如果你想根据状态进行过滤,你可以将一个 filter 方法串到你计算的 属性 posts

的末尾

类似这样的事情

posts() {
      if (this.rawPosts.length && this.users.length) {
        return this.rawPosts.map(rawPost => ({
          ...rawPost,
          user: this.userFrom(rawPost.userId)
        })).filter(post => post.status == this.selected);
      } else {
        console.log("some not assigned");
      }
    }

我所做的就是添加这个

.filter(post => post.status == this.selected);

更新:或者如果你想显示每个选中的状态,你可以这样做

 .filter(post => this.selected.includes(post.status));

我已经编辑了CodeSandbox..这样的东西应该可以工作:

编辑: 对其进行了清理,使其更接近您最初拥有的内容(将 watch 更改为computed 属性 并将变量重命名为您为它们命名的名称)..

Edit2: 这是我的最终产品 - 对其进行了更多清理,使其更短且更易于阅读。



代码沙盒:



代码段:

new Vue({
  el: "#app",
  data() {
    return {
      filter: null,
      selected: ["open"], // Must be an array reference!
      options: [
        { text: "Open", value: "open" },
        { text: "Assigned", value: "assigned" },
        { text: "Pending", value: "pending" },
        { text: "Closed", value: "closed" }
      ],
      rawPosts: [
        {
          userId: 1,
          status: "open",
          id: 1,
          title:
            "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
          body:
            "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        },
        {
          userId: 1,
          status: "open",
          id: 2,
          title: "qui est esse",
          body:
            "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
        },
        {
          userId: 2,
          status: "closed",
          id: 3,
          title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
          body:
            "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
        },
        {
          userId: 2,
          status: "assigned",
          id: 4,
          title: "eum et est occaecati",
          body:
            "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
        },
        {
          userId: 4,
          status: "pending",
          id: 5,
          title: "nesciunt quas odio",
          body:
            "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
        }
      ],
      users: [
        {
          uid: 1,
          firstname: "Claiborne",
          lastname: "Heberden",
          email: "cheberden0@gravatar.com"
        },
        {
          uid: 2,
          firstname: "Gerick",
          lastname: "Tetla",
          email: "gtetla1@whitehouse.gov"
        },
        {
          uid: 3,
          firstname: "Raymund",
          lastname: "Espy",
          email: "respy2@freewebs.com"
        },
        {
          uid: 4,
          firstname: "Dilly",
          lastname: "Dimitriev",
          email: "ddimitriev3@skype.com"
        },
        {
          uid: 5,
          firstname: "Roby",
          lastname: "Tabner",
          email: "rtabner4@sohu.com"
        }
      ],
      fields: [
        { key: "id" },
        { key: "title" },
        { key: "body" },
        { key: "user", label: "Assigned To" }
      ]
    };
  },
  created() {
    //this.loadPosts();
    //this.loadNames();
  },
  methods: {
    userFrom(id) {
      const user = this.users.find(user => user.uid === id);
      return user ? `${user.lastname}, ${user.firstname}` : "not assigned";
    },
    postsFromStatus() {
      return this.rawPosts.filter(o => this.selected.includes(o.status));
    },
    mapPostsAndUsers(posts) {
      return posts.map(post => ({
        ...post,
        user: this.userFrom(post.userId)
      }));
    }
  },
  computed: {
    posts() {
      return this.rawPosts.length && this.users.length
        ? this.selected.length === 0
          ? this.mapPostsAndUsers(this.rawPosts)
          : this.mapPostsAndUsers(this.postsFromStatus())
        : console.log("some not assigned");
    }
  }
})
#app {
  background-color: #fefefe;
  padding: 1rem 2rem 0 2rem;
  border: none !important;
  margin-bottom: 1rem;
}

/** ADDED FOR BREVITY
 *  REMOVE THIS TO SEE ALL DATA IN A CELL*/
td {
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
/** */
<script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<link href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" rel="stylesheet"/>

<div id="app">
  <div class="main">
    <b-container>
      <b-form-group label>
        <b-input-group>
          <b-form-input v-model="filter" placeholder="Type to search for a specific issue"></b-form-input>
          <b-input-group-append>
            <b-button :disabled="!filter" @click="filter = ''">Clear</b-button>
          </b-input-group-append>
        </b-input-group>
      </b-form-group>
      <b-form-group label="View Status:">
        <b-form-checkbox-group id="checkbox-group-1" v-model="selected" :options="options" name="flavour-1"></b-form-checkbox-group>
      </b-form-group>
      <b-table :items="posts" :fields="fields" :filter="filter">
        <!-- A custom formatted column -->
        <template slot="name" slot-scope="data">{{ data.value.user }}</template>
      </b-table>
    </b-container>
  </div>
</div>



CodePen:

Click here for CodePen