I wrote a simple .vue file that is supposed to show a text input, that when focused displays a list of items. What I am struggling with is that I would like that when i click on an item, it sets the value of the text input to this item. However, right now with my code, the div containing the items hides before the click event triggers.
How can I do to perform the click event before the hiding ?
Here is my code :
<script>
export default {
name: 'ListCompletion',
data() {
return {
placeholder: "Gamertag",
items: ['1', '2', '3', '4'],
toggle: false
}
}
};
</script>
<template>
<div >
<input ref="input" type="text" :placeholder="placeholder" @focus="toggle = true" @blur="toggle = false" />
<div v-show="toggle" >
<button type="button" v-for="item in items" @click="$refs.input.value = item">
{{ item }}
</button>
</div>
</div>
</template>
Thanks in advance for the help.
CodePudding user response:
you could try @mousedown
instead. It should trigger before the @blur
event.
<script>
export default {
name: 'ListCompletion',
data() {
return {
placeholder: "Gamertag",
items: ['1', '2', '3', '4'],
toggle: false
}
}
};
</script>
<template>
<div >
<input ref="input" type="text" :placeholder="placeholder" @focus="toggle = true" @blur="toggle = false" />
<div v-show="toggle" >
<button type="button" v-for="item in items" @mousedown="$refs.input.value = item">
{{ item }}
</button>
</div>
</div>
</template>
CodePudding user response:
You can use setTimeout:
new Vue({
el: "#demo",
data() {
return {
placeholder: "Gamertag",
items: ['1', '2', '3', '4'],
toggle: false
}
},
methods: {
handleToggle() {
setTimeout(() => this.toggle = false, 500)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div >
<input ref="input" type="text" :placeholder="placeholder"
@focus="toggle = true" @blur="handleToggle" />
<div v-show="toggle" >
<button type="button"
v-for="item in items" :key="item" @click="$refs.input.value = item">
{{ item }}
</button>
</div>
</div>
</div>