Help us understand the problem. What is going on with this article?

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

オブジェクト型(数値、文字列、論理値などプリミティブではない型)を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>

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away