LoginSignup
0
0

More than 3 years have passed since last update.

Vue.js の slot を使用して並べ替えと絞り込みを行う (v2.5 以前で v2.6 からは deprecated になりそう)

Last updated at Posted at 2019-06-06

slot を使用しての並べ替えと絞り込み

実装例
上記において { pref } の値によるまとまりの並べ替えと
内容となる list 自体の反転を行っています。

props の指定により name を変更する slot

list の並べ替えに使用するコンポーネントとなります。

  • 子コンポーネント自体には表示対象となる list を持たせません。
  • slotname の指定に props からの関数を使用させます。
  • slot を並べ替える基となる sortListprops として渡します。
DynamicSlot
<template>
  <div>dynamic
    <slot v-for="(row, key) in sortList" :name="slotName(row, key)">
      <!-- slot タグには :key 指定ができない模様 -->
      <span :key="slotName(row, key)"></span>
    </slot>
  </div>
</template>

<script>
import Vue from "vue";
export default Vue.extend({
  props: {
    sortList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    slotName: {
      type: Function,
      default: (row, key) => `dynamic-${key}`
    }
  }
});
</script>

slot による並べ替えコンポーネントの使用

以下の実装をしています。

  • 表示データとなる listpref を並べ替える根拠となる sortListdata に指定
  • 前述の slotname を指定するための slotNamemethods
  • 配列操作として list sortList の反転操作、各要素ごとの pref へのインクリメント
    • prefsortList に含まれない値になった時点で表示対象より除外されます。
App.vue
<template>
  <div id="app">
    <button @click="sortList = sortList.reverse()">pref</button>
    <button @click="list = list.reverse()">list reverse</button>
    <DynamicSlot :sort-list="sortList" :slot-name="slotName">
      <p v-for="(row, key) in list" :key="key" :slot="slotName(row, key)">
        {{ row }}
        <button @click="list[key].pref = list[key].pref + 1">pref increment</button>
      </p>
    </DynamicSlot>
  </div>
</template>

<script>
import DynamicSlot from "./components/DynamicSlot";

export default {
  components: {
    DynamicSlot
  },
  data() {
    return {
      sortList: [{ pref: 2 }, { pref: 3 }, { pref: 1 }],
      list: [
        { id: 1, name: "aaa", pref: 1 },
        { id: 2, name: "bbb", pref: 2 },
        { id: 3, name: "ccc", pref: 1 },
        { id: 4, name: "ddd", pref: 3 },
        { id: 5, name: "eee", pref: 2 },
        { id: 6, name: "fff", pref: 1 },
        { id: 7, name: "ggg", pref: 1 },
        { id: 8, name: "hhh", pref: 3 },
        { id: 9, name: "iii", pref: 3 },
        { id: 10, name: "jjj", pref: 1 }
      ]
    };
  },
  methods: {
    slotName(row, key) {
      return `dynamic-${row.pref}`;
    }
  }
};
</script>

pref の値を基に slotName の結果が変更されますが、
sortList の反転により並び変わるのは こちらの挙動 を利用しており
バグっぽいような感じもしなくもないです・・・。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0