zoukankan      html  css  js  c++  java
  • 基于elementUI二次封装下拉框学年组件selecte组件(优化上一篇)

    优化点:选中的年份由父组件传入,不传即默认为空

    step:

    1、SchoolYear.vue:
    <template>
      <el-select v-model="currentYear">
        <el-option v-for="item in tempYearList" :key="item.value" :label="`${item.text}学年`" :value="item.value" />
      </el-select>
    </template>
    <script>
    export default {
      model: {
        prop: 'selectedYear', // 默认值value,如果props中用value接收来自父组件的v-model值,那么这里可以不写prop
        event: 'yearChange' // 默认值input事件,如果$emit触发input事件,那么这里可以不写event
      },
      props: {
        yearList: Array,
        selectedYear: Number // model.prop为selectedYear,这里就用selectedYear接收,默认是'value'
        // value: Number
      },
      watch: {
        currentYear: {
          handler(newVal) {
            this.$emit('yearChange', newVal)
            // this.$emit('input', newVal)
          }
        }
      },
      data() {
        return {
          currentYear: this.selectedYear,
          // currentYear: this.value,
          tempYearList: []
        }
      },
      created() {
        this.yearList && this.yearList.length
          ? (this.tempYearList = this.yearList)
          : (this.tempYearList = [
              {
                text: '2022',
                value: 2022
              },
              {
                text: '2021',
                value: 2021
              },
              {
                text: '2020',
                value: 2020
              }
            ])
      }
    }
    </script>

    2、引入并使用:

      data() {
        return {
          selected: 2020
      },
      methods: {
        handleSubmit() {
          console.log('已选年份', this.selected)
        }
      }
        <SchoolYear v-model="selected"></SchoolYear>
        <SchoolYear :selectedYear="selected" @yearChange="selected=$event"></SchoolYear>
        <button @click="handleSubmit">点击</button>

    注意:如果使用v-model="selected"去替代:selectedYear="selected" @yearChange="selected=$event",那么SchoolYear.vue组件中必须要重新声明model的prop和event,否则不用声明。

  • 相关阅读:
    Swift语法基础: 20
    Swift语法基础:19
    Swift语法基础:18
    Swift语法基础:17
    Swift语法基础:16
    Swift语法基础:15
    Swift语法基础:14
    Swift语法基础:13
    Swift语法基础:12
    Swift语法基础:11
  • 原文地址:https://www.cnblogs.com/wuqilang/p/14999985.html
Copyright © 2011-2022 走看看