0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue.js でリストにフィルターをかける

Last updated at Posted at 2021-01-13

初めに

公式ドキュメントにフィルターされた結果の表示の方法があった。ドキュメントでは算出プロパティを用いていたので、最近勉強したメソッドと v-if ディレクティブを使って同じ結果になることを確認してみた。
https://jp.vuejs.org/v2/guide/list.html

  <div id="app">
    <li v-for="n in numbers">{{ n }}</li>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    numbers: [ 1, 2, 3, 4, 5 ]
  }
})
  • 動作結果

image.png

算出プロパティでの結果

  <div id="app">
    <li v-for="n in evenNumbers">{{ n }}</li>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    numbers: [ 1, 2, 3, 4, 5 ]
  },
  computed: {
    evenNumbers: function () {
      return this.numbers.filter(function (number) {
        return number % 2 === 0
      })
    }
  }
})
  • 動作結果

image.png

メソッドを用いる方法

こちらは算出プロパティとほとんど変わらない。ただ v-for の中に()を書くことをよく忘れてしまう。

  <div id="app">
    <li v-for="n in evenNumbers()">{{ n }}</li>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    numbers: [ 1, 2, 3, 4, 5 ]
  },
  methods: {
    evenNumbers: function () {
      return this.numbers.filter(function (number) {
        return number % 2 === 0
      })
    }
  }
})
  • 動作結果

image.png

v-if を用いる方法

v-if の中に条件式を書くだけで動いた。

  <div id="app">
    <li v-for="n in numbers" v-if="n % 2 == 0">{{ n }}</li>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    numbers: [ 1, 2, 3, 4, 5 ]
  }
})
  • 動作結果

image.png

参考記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?