优化点:选中的年份由父组件传入,不传即默认为空
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,否则不用声明。