SoFunction
Updated on 2025-04-10

el-select binding default value method in vue

vue's el-select binding default value

vue select drop-down box binding default value:

First, add value to option so that v-model can get the corresponding selected value

1. When there is no binding v-model, directly add selected attributes to the corresponding option

2. When select is bound to the value of v-model, write the default value in the data value bound to the v-model.

The problem of el-option bound value cannot be selected

The problem that the select binding value v-model in the framework vue-element-ui cannot automatically select option

The code is as follows:

<template>
 <el-select v-model="" placeholder="choose">
   <el-option
     v-for="item in colorOptions"
     :key=""
     :label=""
     :value="">
   </el-option>
 </el-select>
<template>
<script>
colors = {
 "1": "yellow",
 "2": "red",
 "3": "green"
}
export default {
  data() {
      return {
          formData:{ colorId: 2 },
          colorOptions: obj2Array(colors)
    }
  }
}
function obj2Array(obj){
  const arr = []
  for(let key in obj){
    ({id:key, name: obj[key]})
  }
  return arr
}
</script>

I found that red cannot be automatically selected, but 2 is displayed directly. What is the problem?

It turns out that it is the problem with the obj2Array method. When refactoring it into an array, the key is given directly to the id, and the colorId is a numeric value, so it cannot be matched.

Correct solution:

function obj2Array(obj){
  const arr = []
  for(let key in obj){
    ({id:Number(key), name: obj[key]})
  }
  return arr
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more.