select to set the default option

question:

After looping out the data in the select, I found that the select box that originally displayed the first item by default has become blank. I want to set a default option. I encountered this problem today, and then summarized two.

Solutions:

The html code is as follows. The selected value can be obtained through v-model. If there is a value attribute in the option, the value value, that is, option.name, will be obtained first. If it does not exist, the text content of the option will be obtained.

1. Static select and option


That is to say , it is very simple in this case without vue dynamic rendering : generally the default is the first one is the default option, if you want other defaults, just add selected

<  select   id  =   "sel"  >
	<  option   value  =  "1"  >1</  option  >
	<  option   value  =  "2"   selected  =  "selected"  >2</  option  >
	<  option   value  =  "3"  >3</  option  >
</  select  >

2. Vue dynamic rendering option

Here I take the one built with elementUI as an example:
the default value needs to be set in the select tag and bound with v-model. The default value can be set outside the rendered array, as long as it is consistent with the value of the option.

<template>
  <div>
    <el-select v-model="value" placeholder="请选择" @change="handleSelect">
      <el-option
        v-for="item in options"
        :key="item.id"
        :value="item.name"
        :label="item.name"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
    
    
  name: 'ceShi',
  data () {
    
    
    return {
    
    
      options: [
        {
    
    
          id: 1,
          name: '老王'
        },
        {
    
    
          id: 2,
          name: '李四'
        }
      ],
      value: ''
    }
  },
  created () {
    
    
    this.value = this.options[0].name
  },
  methods: {
    
    
    handleSelect () {
    
    
      console.log(this.value)
    }
  }
}
</script>

<style>
</style>


The hidden attribute is that
when we assign the value in v-model, that is, the value in data, to the value in the option of the loop, then this option will be selected by default

My original idea was to make a ternary expression for the selected attribute of option, but the result was not working:

:selected="item.id == 1 ? selected : ''"

Learn from it.
Actual effect:
insert image description here

Guess you like

Origin blog.csdn.net/qq_45382872/article/details/126897723