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 v-modelで更新された配列を随時ソートする

Posted at

ちょっとハマったところ

watchで自分自身を変更すると無限ループにハマるので新旧データを数を見比べて値の増減があったときのみソートとする。

コード

new Vue({
  el: '.app',
  watch: {
    checkedPrefectures(oldVal, newVal) {
      // このIFがないと無限ループが発生する
      if (oldVal.length !== newVal.length) {
        this.checkedPrefectures.sort((a, b) => b.code - a.code)
      }
    }
  },
  data: {
    checkedPrefectures: [], // 選択済み都道府県
    prefectures: [
      { "code": 1, "name": "北海道"},
      { "code": 2, "name": "青森県"},
      { "code": 3, "name": "岩手県"},
      // ...etc
    ]
  }
});

選択された都道府県をID降順で並び替えて表示するサンプル

See the Pen by MA (@micro_jp_) on CodePen.

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?