My task involves creating a list of musical instruments that triggers an auto-suggest feature in a c-input component when users start typing. Additionally, I need the ability to dynamically add or remove the auto-suggest functionality from the c-input component.
/* instrument component */
<template>
<c-input ref="input"
:values="inputValue"
:placeholder="placeholder"
@input="onInput"
@change="onChangeInput"
@reset="reset" />
<autosuggest
v-if="showSuggests"
:inputValue="inputValue"
:suggests="suggests"
@onSelectRic="selectRicFromList"
></autosuggest>
</div>
</template>
<script>
export default {
name: 'instrument',
data: () => ({
suggests: [],
inputValue: '',
}),
computed: {
showSuggests() {
return this.isNeedAutosuggest && this.showList;
},
showList() {
return this.$store.state.autosuggest.show;
},
isloading() {
return this.$store.state.instruments.showLoading;
},
defaultValue() {
if (this.instrument.name) {
return this.instrument.name;
}
return '';
},
},
[...]
};
</script>
I'm dealing with a parent component that looks like this:
<template>
<div>
<instrument v-for="(instrument, index) in instruments"
:key="instrument.name"
:instrument="instrument"
:placeholder="$t('change_instrument')"
:isNeedAutosuggest="true" /> <!--that flag should manage an autosuggest option-->
<instrument v-if="instruments.length < maxInstruments"
ref="newInstrument"
:isNeedAutosuggest="true" <!-- here too -->
:placeholder="$t('instrument-panel.ADD_INSTRUMENT')" />
</div>
</template>
The issue I am facing is that for each instrument in the list, there is a corresponding auto-suggest component displayed in the DOM. Ideally, there should only be one auto-suggest component active at a time based on certain conditions. Moving the auto-suggest functionality to the parent level is not ideal due to flexibility concerns and its close association with the c-input element.
Do you have any suggestions on how to address this?
[UPDATE]
This is how I resolved it:
I created a separate wrapper component that encapsulates both the input and auto-suggest components. If an input requires auto-suggest functionality, this wrapper component is used; otherwise, a simple input component is utilized.
/* wrapper.vue - inserted into Instrument.vue */
<template>
<span>
<fc-input ref="input"
:values="value"
:placeholder="placeholder"
:isloading="isloading"
@input="onInput"
@changeInput="$emit('change', $event)"
@resetInput="onResetInput" />
<fc-autosuggest
v-if="isSuggestsExist"
:suggests="suggests"
/>
</span>
</template>