-
Notifications
You must be signed in to change notification settings - Fork 11
/
vue-chosen.vue
131 lines (118 loc) · 3.74 KB
/
vue-chosen.vue
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<template>
<select :data-placeholder="placeholder" :multiple="multiple" :disabled="disabled">
<option v-for="option in localOptions" v-bind:value="option[trackBy]">
{{ option[label] }}
</option>
</select>
</template>
<script>
export default {
props: {
value: {
type: [String, Number, Array, Object],
default: null
},
options: {
type: [Array, Object],
default: () => []
},
label: {
type: String,
default: 'label'
},
trackBy: {
type: String,
default: 'id'
},
multiple: {
type: Boolean,
default: false
},
placeholder: {
type: String,
default: 'Select'
},
searchable: {
type: Boolean,
default: true
},
searchableMin: {
type: Number,
default: 1
},
allowEmpty: {
type: Boolean,
default: true
},
allowAll: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
onValueReturn: {
type: Object,
default: () => ({})
}
},
computed: {
localOptions() {
let vm = this,
options = []
if (this.allowAll) {
options.push({
[this.trackBy]: -1,
[this.label]: 'All'
})
}
if (Array.isArray(this.options)) {
return options.concat(this.options)
}
Object.keys(this.options).forEach(function (key) {
options.push({
[vm.trackBy]: key,
[vm.label]: vm.options[key]
})
})
return this.allowEmpty
? [{ [this.trackBy]: null, [this.label]: '' }].concat(options)
: options
},
localValue() {
let value = this.allowAll && this.value === null ? -1 : this.value
this.$nextTick(function () {
$(this.$el).val(value).trigger("chosen:updated")
})
return value
}
},
watch: {
localValue() {
},
localOptions() {
this.$nextTick(function () {
let value = this.allowAll && this.value === null ? '-1' : this.value
$(this.$el).val(value).trigger("chosen:updated")
})
}
},
mounted() {
let component = this
$(this.$el).chosen({
width: "100%",
disable_search_threshold: this.searchable ? this.searchableMin : 100000
}).change(function ($event) {
const value = $($event.target).val()
if (typeof component.onValueReturn[value] !== 'undefined') {
return component.$emit('input', component.onValueReturn[value])
}
if (component.allowAll && ($($event.target).val() === '-1' || $($event.target).val() === -1)) {
return component.$emit('input', null)
}
component.$emit('input', $($event.target).val())
})
}
}
</script>