20
7

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 5 years have passed since last update.

Vue.jsでselectタグの初期値にオブジェクトを設定する際の注意

Last updated at Posted at 2019-12-02

オブジェクト型(数値、文字列、論理値などプリミティブではない型)をoptionの値に設定

 以下のように、オブジェクト型を選択肢に設定して、そのデフォルト値を「v-model」で指定することができます。
 例の場合は、「selectedInfo」に「code=2」の値を設定しています。

sample.vue

<template>
 <select v-model="selectedInfo"><!-- ★ v-modelに初期値オブジェクトを設定 -->
  <option v-for="info in infoList" :value="info"><!-- ★ valueにinfoというオブジェクトを設定 -->
   {{ info.label }}
  </option>
 </select>
</template>
<script>
export default {
 data() {
   return {
     //初期値
     selectedInfo: { code: '2', label: '2番' },
     //選択肢
     infoList: [
       {code: '1', label: '1番'},
       {code: '2', label: '2番'},
       {code: '3', label: '3番'},
       {code: '4', label: '4番'},      
     ]
   }
 }
}
</script>

選択値(v-modelの値)は、プロパティや値が選択肢と完全に一致していないと選択されない

以下の例だと、remarkプロパティがないので選択されない。

sample.vue

<template>
 <select v-model="selectedInfo"> <!-- ★ opitonに設定したオブジェクトと完全に一致しないので選択されない -->
  <option v-for="info in infoList" :value="info">
   {{ info.label }}
  </option>
 </select>
</template>
<script>
export default {
 data() {
   return {
     selectedInfo: { code: '2', label: '2番' },// ★ remarkというプロパティがない
     infoList: [
       {code: '1', label: '1番', remark: '' },
       {code: '2', label: '2番', remark: '' },
       {code: '3', label: '3番', remark: '' },
       {code: '4', label: '4番', remark: '' },      
     ]
   }
 }
}
</script>

20
7
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
20
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?