elementUI select組件 默認選擇第一項


場景:后台返回最近醫保年 5個年份的數據 [2019,2018,2017,2016,2015],將數據以props形式傳入 searchForm組件 並以select形式作為搜索條件展示,默認選中最近一年

 

情況一:已知select options數組 如下設置:

export default {
    data() {
      return {
        options: [{
          value: '選項1',
          label: '黃金糕'
        }, {
          value: '選項2',
          label: '雙皮奶'
        }, {
          value: '選項3',
          label: '蚵仔煎'
        }, {
          value: '選項4',
          label: '龍須面'
        }, {
          value: '選項5',
          label: '北京烤鴨'
        }],
        value: '選項1'
      }
    }
  }

  情況二:回到開始的場景

 處理數據

  =>將[2019,2018,2017,2016,2015] 轉為符合 options的數據格式

  =>[{label:2019,value:2019},{label:2018,value:2018},{label:2017,value:2017},{label:2016,value:2016},{label:2015,value:2015}],

  =>子組件接收 options ,並設置v-model="value" 的value = this.options[0].value;

父組件

<template>
  <div class="hello">
      <item :options="resArr"></item>
  </div>
</template>

<script>
import item from './a';
export default {
  name: 'HelloWorld',
  components:{
    item
  },
  data () {
    return {
      optionArr:[2019,2018,2017,2016,2015],
      resArr:[]
    }
  },
  created() {
    this.init();
  },
  methods: {
    init(){
      for(var val of this.optionArr){
        this.resArr.push({label:val,value:val})
      }

    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>


子組件
<template>
  <div>
    <el-select v-model="value" style="width:240px;" placeholder="請選擇">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>

<script>
  export default {
    name:'item',
    props:{
      options:{
        type:Array,
        default:()=>{
          return [];
        }
      }
    },
    data() {
      return {
        value:''
      }
    },
    created() {
      this.value = this.options[0].value;
    },
  }
</script>

<style scoped>
</style>

  

  

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM