LoginSignup
1
0

More than 3 years have passed since last update.

【Vue.js】v-forで回ってきたオブジェクトをcomputedにデータとして保持する

Posted at

はじめに

このようなデータがv-forで使用され、中身のオブジェクトをデータとして保持したい時がある。
その時の例を備忘録として残す。

data () {
    return {
      members: [
        {
          id: 1,
          name: 'sato'
        },
        {
          id: 2,
          name: 'tanaka'
        },
        {
          id: 3,
          name: 'kobayashi'
        }
      ],
    }   
  }

選択要素のidを取得

  1. レンダリングされたnameの元のオブジェクトからidを取得するイベントを設定する。
  2. 取得したidをもとにdataに保持
data() {
  return {
    selectedMemberId: undefined
  }
},
methods: {
 setId: function () {
          this.selectedMemberId = member.id //membersのオブジェクト
        }
}

取得したidを元にオブジェクトをデータとして保持

lodashを使って配列操作
1. vueインスタンスを変数に代入
2. 取得したidと一番最初に一致するidをもつオブジェクトを返す

computed: {
  currentMember: function () {
      const self = this
      return _.find(self.members, function (member) {
        return thumb.id === self.selectedMemberId
      })
    },

computedの中身

  • スコープがcurrentMemberになってしまうためvueインスタンスを変数に代入
  • _.find(lodash.find)は条件に一致する一番最初の要素を取得
1
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
1
0