const AutoCompleteComponent = {
data() {
return {
open: false,
current: 0,
/** @type {string[]} **/
suggestions: ["first", "ble", "hello"],
fieldWidth: 0,
}
},
mounted() {
this.fieldWidth = this.$refs.inputField.clientWidth;
},
methods: {
focus() {
console.log("Focus activated");
this.open = true;
},
blur() {
console.log("Focus deactivated")
// when I do this, the suggestions dissappear the frame before they are
// clicked, causing the suggestionClick to not be called
this.open = false;
},
//For highlighting element
isActive(index) {
return index === this.current;
},
//When the user changes input
change() {
this.loadSuggestions();
//console.log("change()");
if (this.open == false) {
this.open = true;
this.current = 0;
}
},
//When one of the suggestion is clicked
suggestionClick(index) {
this.currentText = this.matches[index];
console.log("Clicked suggestion: ", index, this.matches[index]);
this.open = false;
},
},
computed: {
/**
* Filtering the suggestion based on the input
* @this {ReturnType}
*/
matches() {
console.log("computed.matches() str=", this.currentText, " suggestions=", this.suggestions);
return this.suggestions.filter((str) => {
const withoutAccents = str.toLowerCase();
return withoutAccents.indexOf(this.currentText.toLowerCase()) >= 0;
});
},
//The flag
openSuggestion() {
return this.currentText !== "" &&
this.matches.length != 0 &&
this.open === true;
},
copiedWidth() {
return this.fieldWidth + "px";
}
},
template: "#vue-auto-complete-template"
};
< /code>
Это шаблон HTML: < /p>
[list]
[*] @click="suggestionClick(suggestion_index)">
{{ suggestion }}
[/list]
< /code>
Итак, тогда я создаю его как: < /p>
< /code>
, чтобы его появились под поле, применяется следующие CSS: < /p>
.auto-complete-field {
display:inline-block;
}
.auto-complete-field .suggestions-wrapper {
display:block;
position: relative;
}
.auto-complete-field.open ul {
display:initial;
}
.auto-complete-field ul {
list-style:none;
padding:0;
margin:0;
display: none;
position: absolute;
top:0px;
left: 0px;
border-bottom: 1px solid black;
}
.auto-complete-field ul li {
background-color: white;
border: 1px solid black;
border-bottom: none;
}
Теперь проблема заключается в том, что если вы посмотрите на функцию blur () , она устанавливает открытие на false, которая, в свою очередь, скрывает предложения Ul.field-suggestions < /code> Использование Active name. Field.open ul до создания события Click, в результате чего его приводит к тому, что он был под ним. this.open = false}, 100) . Я думаю, что для работы, тайм -аут на самом деле должен быть двумя кадрами, по крайней мере. Это не сработало как микротаска и не запросов анимации . Я не хочу использовать тайм -аут, особенно большой, потому что он может вызвать мерцание графического интерфейса с помощью быстрых кликов. < /P>
Я ищу более надежное решение для этого. Я надеюсь, что у Ву что есть что -то для этого. Обычное решение JS, как правило, является переосмыслением события размытия, прослушивая несколько событий в окне и проверяя, где они произошли. Я бы предпочел избегать этого.
blur() { console.log("Focus deactivated") // when I do this, the suggestions dissappear the frame before they are // clicked, causing the suggestionClick to not be called this.open = false; },
//For highlighting element isActive(index) { return index === this.current; },
//When the user changes input change() { this.loadSuggestions(); //console.log("change()"); if (this.open == false) { this.open = true; this.current = 0; } },
//When one of the suggestion is clicked suggestionClick(index) { this.currentText = this.matches[index]; console.log("Clicked suggestion: ", index, this.matches[index]); this.open = false; }, }, computed: {
/** * Filtering the suggestion based on the input * @this {ReturnType} */ matches() { console.log("computed.matches() str=", this.currentText, " suggestions=", this.suggestions); return this.suggestions.filter((str) => { const withoutAccents = str.toLowerCase(); return withoutAccents.indexOf(this.currentText.toLowerCase()) >= 0; }); },
< /code> , чтобы его появились под поле, применяется следующие CSS: < /p> .auto-complete-field { display:inline-block; } .auto-complete-field .suggestions-wrapper { display:block; position: relative; }
.auto-complete-field.open ul { display:initial; }
.auto-complete-field ul { list-style:none; padding:0; margin:0;
display: none;
position: absolute; top:0px; left: 0px;
border-bottom: 1px solid black; } .auto-complete-field ul li { background-color: white; border: 1px solid black; border-bottom: none; } [/code] Теперь проблема заключается в том, что если вы посмотрите на функцию blur () , она устанавливает открытие на false, которая, в свою очередь, скрывает предложения Ul.field-suggestions < /code> Использование Active name. Field.open ul до создания события Click, в результате чего его приводит к тому, что он был под ним. this.open = false}, 100) . Я думаю, что для работы, тайм -аут на самом деле должен быть двумя кадрами, по крайней мере. Это не сработало как микротаска и не запросов анимации . Я не хочу использовать тайм -аут, особенно большой, потому что он может вызвать мерцание графического интерфейса с помощью быстрых кликов. < /P> Я ищу более надежное решение для этого. Я надеюсь, что у Ву что есть что -то для этого. Обычное решение JS, как правило, является переосмыслением события размытия, прослушивая несколько событий в окне и проверяя, где они произошли. Я бы предпочел избегать этого.