Cascader.vue
3.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<template>
<a-cascader v-model:value="cascaderValue" :show-search="showSearch" :changeOnSelect="changeOnSelect" expand-trigger="hover" :options="options" @change="onChange" :placeholder="placeholder"
:bordered="bordered" :show-arrow="showArrow"/>
</template>
<script lang="ts">
import {Component, Model, Prop, toNative, Vue, Watch} from "vue-facing-decorator";
import {SimpleTreeItem} from "lib/src/core/bean/SimpleTreeItem";
@Component({
name: "MCascader",
components: {}
})
export default class Cascader extends Vue {
@Model({required: true, name: "value"})
value: any;
@Prop({required: true, type: Array})
options: [];
@Prop({required: false, type: String})
placeholder: string;
@Prop({required: false, type: String})
keyName: string;
@Prop({required: false, type: Boolean, default: false})
showSearch: boolean;
@Prop({required: false, type: Boolean, default: true})
bordered: boolean;
@Prop({required: false, type: Boolean, default: true})
showArrow: boolean;
@Prop({required: false, type: Boolean, default: false})
changeOnSelect: boolean;
cascaderValue: string[] = null;
onChange(value, selectedOptions): void {
if (value) {
const leafValue = value[value.length - 1];
if (this.keyName) {
const newObj = {};
newObj[this.keyName] = leafValue;
this.$emit('update:value', newObj);
} else {
this.$emit('update:value', leafValue);
}
} else {
this.$emit('update:value', null);
}
this.$emit('change', value, selectedOptions);
}
@Watch('value', {deep: true, immediate: true})
watchValue(newValue: any, oldValue: any): void {
this.conventValue();
}
@Watch('options', {deep: true, immediate: true})
watchOptions(newValue: SimpleTreeItem, oldValue: SimpleTreeItem): void {
if (newValue !== oldValue) {
this.conventValue();
}
}
conventValue(): void {
if (this.options && this.value) {
const leafValue = (this.keyName ? this.value[this.keyName] : this.value) + "";
if (this.cascaderValue != null && this.cascaderValue.length > 0 && this.cascaderValue[this.cascaderValue.length - 1] === leafValue) {
return;
}
const values = [];
this.recurTree(this.options, leafValue, values);
if (values.length > 1) {
this.cascaderValue = values.reverse();
} else {
this.cascaderValue = values;
}
}
}
recurTree(options: SimpleTreeItem[], recurValue: string, values: string[]): boolean {
let matched = false;
for (const option of options) {
if (option.value === recurValue) {
values.push(option.value);
matched = true;
break;
}
if (option.children) {
matched = this.recurTree(option.children, recurValue, values);
if (matched) {
values.push(option.value);
break;
}
}
}
return matched;
}
}
</script>
<style lang="less" scoped>
</style>