Last week it was demand again. Well, bring it on
Start with the requirements goals to achieve the functionality
- Focus on historical search (cache)
- The clear cache button appears under the history search
- Input returns a cue based on the background
One of the most useful components in ElementUi is the el-AutoComplete component, but adding a clear button to the component is a bit of a hassle. Because the slot for el-AutoComplete is for each item in the frame, not the whole frame, I push the empty cache button as an option into the prompter array, and then style the item; Second, the watch detection will be used to match the cue based on the input, rather than the input or change event
Let’s go to the HTML section
<el-autocomplete ref="input1" hide-loading class="inline-input" v-model="search_word" :fetch-suggestions="querySearch" placeholder="Please enter the content">
<template slot-scope="{ item }">
<div @click.stop="goSearch(item.value)" :class="Item. value === 'Clear history search '? 'clearStorage':''">{{ item.value }}</div>
</template>
<el-select v-model="selectCato" slot="prepend" placeholder="Please select">
<el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions" :key="index"></el-option>
</el-select>
<el-button slot="append" icon="el-icon-search" @click="getResult(search_word, selectCato); getCatogary(search_word, selectCato); pagination.current = 1"></el-button> <! -- </el-input> --> </el-autocomplete>Copy the code
It is worth noting that the ref is set for the el-AutoComplete component, because we will not set the change event, so we need to unpack the popbox manually
Then there’s the JS part
querySearch (queryString, cb) {
letResults = null // Call callback to return data for the list of suggestionsif(! queryString) {if (this.OldSearch.length) {
results = this.OldSearch.map((item, index) => {
return {value: item, index: index+1}
})
results.push({value: 'Clear history Search', index: this.OldSearch.length+1})
} else {
results = []
}
} else {
results = this.complete_word
}
cb(results)
},
Copy the code
Here, it is necessary to determine whether the words have been entered. If not, the cached words will be displayed, and if there are, the prompter will be displayed. Pressing the word selection will trigger the event of closing the pop-up box
None example Close the subrack event
goSearch (word) {
if(word ! = ='Clear history Search') {
this.search_word = word
this.$nextTick(() => {
this.$refs.input1.close()
this.$refs.input1.$children[0].blur()
this.$refs.input2.close()
this.$refs.input2.$children[0].blur()
}
} else {
this.delSearchStorage()
this.$nextTick(() => {
this.$refs.input1.close()
this.$refs.input1.$children[0].blur()
this.$refs.input2.close()
this.$refs.input2.$children[0].blur()
})
}
},
Copy the code
The finished product