基于element UI二次封装下拉组件

252 阅读1分钟

组件:SelectYear/index.vue

<template>
  <el-select v-model="currentValue" v-bind="$attrs">
    <el-option v-for="item in tempOptions" :key="item.id" :label="item.title" :value="item.id" />
  </el-select>
</template>
<script>
export default {
  props: {
    value: { type: Number | String, require: true },
    options: { type: Array, default: () => [] }
  },
  methods: {
    getOptions() {
      this.tempOptions = [
        { id: 2021, title: '2021学年' },
        { id: 2022, title: '2022学年' },
        { id: 2023, title: '2023学年' }
      ]
    }
  },
  data() {
    return { tempOptions: [] }
  },
  computed: {
    currentValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    const { options } = this
    options?.length ? (this.tempOptions = options) : this.getOptions()
  }
}
</script>

使用

    <SelectYear v-model="year" placeholder='选择年份' filterable clearable :options='options' />

说明

  1. v-model是input事件和value属性的语法糖,所以computed中可以获取到value,并且可以触发input事件
  2. v-bind="$attrs"可以获取从父组件中接收到的,没有注册到props中的值,像placeholder这些属性不用在子组件中props中接收,直接绑定到组件上
  3. 如果传递了可用的options,那么组件中不需要再请求接口

抽时间研究下ProjectRemoteOptions