Skip to content

Instantly share code, notes, and snippets.

@lpj145
Created May 18, 2021 12:55
Show Gist options
  • Save lpj145/61caeb0cecf6569d40d704b24f078300 to your computer and use it in GitHub Desktop.
Save lpj145/61caeb0cecf6569d40d704b24f078300 to your computer and use it in GitHub Desktop.
<script>
import { debounce } from '@/utils/function'
import httpClient from '@/utils/httpClient'
export default {
name: 'VAutocompleteServer',
props: {
value: {
type: [Array, Object, Number, String],
default: () => ([])
},
debounceTime: {
type: [Number, String],
default: 400
},
label: {
type: String,
required: true,
},
itemText: {
type: String,
required: true
},
itemValue: {
type: String,
required: true
},
url: {
type: String,
required: true
},
param: {
type: String,
default: null
},
resumeSelected: Boolean,
returnObject: Boolean,
dense: Boolean,
multiple: Boolean,
autoCreate: Boolean,
hint: {
type: String,
default: ''
}
},
data: () => ({
items: [],
loading: false,
}),
methods: {
search (value, keyCode) {
if (['ArrowDown', 'ArrowUp', 'Escape', 'Enter', 'Space', 'Backspace'].includes(keyCode)) return
const config = {
params: {
noPage: true
}
}
if (this.param) {
config.params[this.param] = value
}
this.$emit('search')
this._debounced(() => {
this.loading = true
httpClient.get(this.url, config)
.then((d) => d.data)
.then((d) => {
if (this.autoCreate && value) {
this.items = [
{ [this.itemValue]: value, [this.itemText]: value },
...this.items,
...d
]
return d
}
this.items = [...this.items, ...d]
})
.finally(() => {
this.loading = false
})
})
}
},
beforeCreate () {
const { debounceTime } = this.$options.propsData
this._debounced = debounce((fn) => fn(), parseInt(debounceTime))
}
}
</script>
<template>
<v-autocomplete
v-bind="$attrs"
:items="items"
:item-value="itemValue"
:item-text="itemText"
:label="label"
:dense="dense"
:return-object="returnObject"
:multiple="multiple"
:loading="loading"
outlined
:hint="hint"
:persistent-hint="!!hint"
@keyup="({ target, code }) => search(target.value, code)"
@change="(value) => $emit('input', value)"
:value="value"
>
<template #selection="{ item, index }" v-if="resumeSelected && multiple">
{{ index === 0 && value.length === 1 ? item[itemText] : '' }}
{{ index === 0 && value.length > 1 ? 'Selecionado:' : '' }}
{{ index === 1 && value.length > 1 ? `(${ value.length })`: '' }}
</template>
</v-autocomplete>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment