VUE/VUEJS AutoCompete textbox as separate componenet and pass parameters
for it. It is own separate control that we can add in any project.
1.
Create a file:
AutoComplete.vue and paste below code
<template>
<div class="autocomplete">
<input
type="text"
v-on:change="getValue"
v-model="mdlAutoText"
v-on:input="getSearchValues"
@keydown.down="onArrowDown"
@keydown.up="onArrowUp"
@keydown.enter="onEnter"
/>
<ul
id="autocomplete-results"
v-show="isOpen"
class="autocomplete-results"
v-bind:style="{ width: aWidth }"
>
<li class="loading" v-if="isLoading">Loading results...</li>
<li
v-else
v-for="(result, i) in results"
v-bind:key="result.T"
@click="setResult(result.T)"
class="autocomplete-result"
:class="{ 'is-active': i === arrowCounter }"
>
{{ result.T }}
</li>
</ul>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "AutoComplete",
components: {},
props: ["items", "apiUrl", "sKey", "aWidth", "charLen"],
data: function () {
return {
mdlAutoText: this.items,
isOpen: false,
results: [],
search: "",
isLoading: false,
arrowCounter: 0,
};
},
methods: {
getValue: function () {
//if (this.isOpen == true) this.$refs.txtAutoComp.focus();
if (this.results.length <= 1) {
this.isOpen = false;
this.$emit("resBasePart", this.mdlAutoText);
}
},
getSearchValues: function () {
if (this.mdlAutoText.length >= this.charLen * 1) {
axios({
method: "get",
url: this.apiUrl + "?p1=" + this.mdlAutoText + "&p2=" + this.sKey,
})
.then((response) => {
let res = JSON.parse(response.data);
this.results = res.Table;
})
.catch(function (err) {
console.log(err);
});
this.isOpen = true;
} else this.isOpen = false;
},
setResult: function (p1) {
this.mdlAutoText = p1;
this.isOpen = false;
this.$emit("resBasePart", this.mdlAutoText);
},
onArrowDown() {
if (this.arrowCounter < this.results.length) {
this.arrowCounter = this.arrowCounter + 1;
}
},
onArrowUp() {
if (this.arrowCounter > 0) {
this.arrowCounter = this.arrowCounter - 1;
}
},
onEnter() {
this.mdlAutoText = this.results[this.arrowCounter].T;
this.isOpen = false;
this.arrowCounter = -1;
},
},
watch: {
items: function (p1) {
//alert(p1 + " " + p2);
this.mdlAutoText = p1;
},
},
};
</script>
<style>
.autocomplete {
position: relative;
}
.autocomplete-results {
padding: 0;
margin: 0;
border: 1px solid #eeeeee;
height: 120px;
overflow: auto;
width: 100%;
position: absolute;
background: white;
z-index: 9999;
}
.autocomplete-result {
list-style: none;
text-align: left;
padding: 0px 2px;
cursor: pointer;
}
.autocomplete-result.is-active,
.autocomplete-result:hover {
background-color: #4aae9b;
color: white;
}
</style>
2.
On parent page add
below code with parameter.
<AutoComplete :items="mdlBasePart" v-on:resBasePart="getBasePart" sKey="parts" apiUrl="http://localhost:5000/Part/GetAutoComp" aWidth="26%" charLen="4" />
3.
Parent page get omitted
value and update model
getBasePart: function (p1) {
this.mdlBasePart = p1;
this.partLoad("part_load");
}
4.
Here we can update key
press Enter, Up arrow and Down arrow