uni-app(Vue)中(picker)用聯動(關聯)選擇以至於完成某些功能

jimyking發表於2021-11-03

如下圖所示,在專案中需求是通過首先選擇學生的專業,選好之後在每個專業下面選擇對應的學期,每個學期有對應的學費,因此就需要聯動選擇來實現這一功能。

以下僅展示此功能主要程式碼:

<div class="item">
				<div class="item-left">
					<span class="star">*</span>
					<span>目標專業 :</span>
				</div>
				<picker mode="selector" :range="majorList.map(v =>v.title)" :value="majorIndex" @change="selectMajor">
					<div :style="majorIndex == 0? 'color:gray':''">{{majorList[majorIndex].title}}</div>
				</picker>
			</div>
			<div class="item">
				<div class="item-left">
					<span class="star">*</span>
					<span>學期 :</span>
				</div>
				<picker mode="selector" :range="termList.map(v => v.title)" :value="termIndex" @change="selectTerm"
					:disabled="majorIndex == 0">
					<div :style="termIndex == 0 ? 'color:gray':''" @click="choseTerm">{{termList[termIndex].title}}
					</div>
				</picker>
			</div>
			<div class="item">
				<div class="item-left">
					<span class="star">*</span>
					<span>雜費及專業特色培訓費 :</span>
				</div>
				<div class="item-right">{{yingjiao_money}}
				</div>
			</div>
export default {
		data() {
			return {
				majorList: [{
					id: 0,
					title: '請選擇專業'
				}],
				majorIndex: 0,
				classList: [{
					id: 0,
					class_name: '請選擇班級'
				}],
				classIndex: 0,
				termList: [{
					term_id: 0,
					title: '請選擇學期'
				}],
				termIndex: 0,
				yingjiao_money: 0,
			}
		},
		methods: {
			//選擇專業
			selectMajor(e) {
				if(this.majorIndex == e.detail.value) {
					return
				} else {
					this.termList = [{ term_id: 0, title: '請選擇學期' }]
					this.majorIndex = e.detail.value
					this.termList = [...this.termList,...this.majorList[e.detail.value].majorFee]
					this.termIndex = 0
					this.yingjiao_money = 0
				}
				
			},
                        //為選擇專業時點選學期提示
			choseTerm () {
				if (this.majorIndex == 0) {
					uni.showToast({
						title: '請先選擇專業',
						icon: 'none'
					})
					return
				}
			},
                        //選擇學期
			selectTerm(e) {
				this.termIndex = e.detail.value
				this.yingjiao_money = this.termList[e.detail.value].price
			}
}

以下圖片展示的為上majorList的資料結構,可根據自己需求進行修改

相關文章