Currently, I am utilizing Vue+Vuetify and facing the task of revamping a custom selector component.
The existing code structure is as follows:
<template>
<v-autocomplete
:id="id"
v-model="internalValue"
:clearable="clearable"
:disabled="disabled"
:hide-details="hideDetails"
:label="label"
:readonly="readonly"
:required="required"
:rules="rules"
:items="items"
item-value="id"
item-text="name"
no-data-text="No data"
/>
</template>
<script>
export default {
name: 'MyCustomSelector',
props: {
value: {
type: String,
default: null,
},
label: {
type: String,
default: '',
},
id: {
type: String,
default: null,
},
required: Boolean,
clearable: Boolean,
hideDetails: Boolean,
disabled: Boolean,
readonly: Boolean,
},
data() {
return {
items: [],
rules: [
(value) => {
if (this.required) {
return !!value || 'This field is empty'
} else {
return true
}
},
],
}
},
apollo: {
// apollo logic
...
this.items = loadedItems
...
},
computed: {
internalValue: {
get() {
return this.value
},
set(newVal) {
this.$emit('input', newVal)
},
},
},
}
</script>
The majority of the code involves passing props
, so I made the decision to transform it into:
<script>
import VAutocomplete from 'vuetify/lib/components/VAutocomplete'
export default VAutocomplete.extend({
name: 'MyCustomSelector',
props: {
itemText: {
type: String,
default: 'name',
},
itemValue: {
type: String,
default: 'id',
},
rules: {
type: Array,
default: () => [
(value) => {
if (this.required) {
return !!value || 'This field is empty'
} else {
return true
}
},
],
},
noDataText: {
type: String,
default: 'No data',
},
},
apollo: {
// apollo logic
...
this.cachedItems = loadedItems
...
},
})
</script>
Although everything seems to be in order, there exists a small issue - the prop
rules
does not function as intended since this.required
is unrecognized.
This prop
is derived from the Validatable
mixin, where the value from the field is simply substituted sequentially to each of the rules
.
Hence, my query pertains to crafting code wherein the behavior of the rule
hinges on the state of the required
field?