哪個網(wǎng)站可以做信用社的題免費發(fā)布推廣的網(wǎng)站
(vue)el-cascader級聯(lián)選擇器按勾選的順序傳值,擺脫層級約束
-
需求:按勾選的順序給后端傳值
-
難點:在 Element UI 的 el-cascader 組件中,默認的行為是根據(jù)數(shù)據(jù)的層級結構來顯示選項,用戶的選擇也會基于這種層級結構,el-cascader 本身并不直接支持自定義的顯示順序。
效果:
實現(xiàn):
// html
<el-cascaderv-model="selectedOptions":options="options":props="props"clearable>
</el-cascader>// js
export default {data(){return {selectedOptions:[],// 綁定的數(shù)組sortSelectedOptions:[],// 排好序的數(shù)組// props: { multiple: true },// 原始獲取到的value是數(shù)字,不方便對比props: { multiple: true, value: 'label', label: 'label' },// 指定value值取labeloptions: [{value: 1,label: '東南',children: [{value: 2,label: '上海',children: [{ value: 3, label: '普陀' },{ value: 4, label: '黃埔' },{ value: 5, label: '徐匯' }]}, {value: 7,label: '江蘇',children: [{ value: 8, label: '南京' },{ value: 9, label: '蘇州' },{ value: 10, label: '無錫' }]}, {value: 12,label: '浙江',children: [{ value: 13, label: '杭州' },{ value: 14, label: '寧波' },{ value: 15, label: '嘉興' }]}]}, {value: 17,label: '西北',children: [{value: 18,label: '陜西',children: [{ value: 19, label: '西安' },{ value: 20, label: '延安' }]}, {value: 21,label: '新疆維吾爾族自治區(qū)',children: [{ value: 22, label: '烏魯木齊' },{ value: 23, label: '克拉瑪依' }]}]}]}}
},
// 監(jiān)聽綁定數(shù)組
watch:{selectedOptions: {handler(newVal, oldValue) {if (newVal.length > oldValue.length) {// 找到新增的項const newItems = this.findNewItems(oldValue, newVal)// 添加到排序數(shù)組中this.sortSelectedOptions.push(...newItems)}if (newVal.length < oldValue.length) {// 找到刪除的項const newItems = this.findNewItems(newVal, oldValue)// 從排序數(shù)組中過濾掉被刪除的項this.sortSelectedOptions = this.sortSelectedOptions.filter(item => {return !newItems.map(e => JSON.stringify(e)).includes(JSON.stringify(item))})}console.log('this.sortSelectedOptions', this.sortSelectedOptions)},deep: true}
},methods:{findNewItems(oldList, newList) {// 創(chuàng)建一個映射表來快速檢查舊列表中的項const oldItemsMap = new Map()for (const item of oldList) {// 使用JSON.stringify作為唯一標識符(注意:如果子數(shù)組順序重要且可能不同,這種方法可能不適用)oldItemsMap.set(JSON.stringify(item), true)}// 遍歷新列表,檢查哪些項不在舊列表中const newItems = []for (const item of newList) {if (!oldItemsMap.has(JSON.stringify(item))) {newItems.push(item)}}return newItems},
}