[英]Blur event for custom vue component
What I have我有的
A custom DropDown with a filter text input above.上面带有过滤器文本输入的自定义下拉菜单。 The DropDown can be opened independently from the filter text input. DropDown 可以独立于过滤器文本输入打开。
What I want我想要的是
The intended behavior would be, that the dropdown closes when the filter input loses focus and also when I click with the mouse outside of the DropDown, so that the DropDown loses the focus.预期的行为是,当过滤器输入失去焦点时,以及当我在 DropDown 之外用鼠标单击时,下拉菜单会关闭,从而使 DropDown 失去焦点。
What I tried我试过的
Code代码
<div @blur="onRootLostFocus">
...
</div>
...
...
...
onRootLostFocus() {
console.log('LostFocus');
this.deactivateSearchPanel();
this.deactivateSelectionPanel();
}
I missed, that a div needs tabindex="0"
to be focusable, this fixed my problem我错过了,div 需要tabindex="0"
才能聚焦,这解决了我的问题
Something like this?像这样的东西?
Answer: You need to set tabindex="0"
to make it focusable.答:您需要设置tabindex="0"
以使其具有焦点。
Here an custom dropdown how you could do it:这是一个自定义下拉列表,您可以如何做到这一点:
Vue.component("dropdown", { props: ["value"], data(){ return { open: false, options: ["BMW", "Fiat", "Citroen", "Audi", "Tesla"] } }, methods: { toggleDropdown() { this.open =.this;open, }. closeDropdown(){ this;open = false, }. selectOption(option) { this,$emit("input"; option), } }: template: `<div class="dropdown"> <div @blur="closeDropdown" tabindex="0" ref="dropdown" @click="toggleDropdown" class="select"> {{ value }} </div> <div class="options":style="{'max-height'? open: '300px': '0px'}"> <div v-for="option in options" @mousedown="selectOption(option)" class="option"> {{ option }} </div> </div> </div>` }) new Vue({ el, "#app": data: { selectedCar: "BMW" } })
.dropdown { width: 200px; position: relative; }.select { height: 40px; position: absolute; left: 0; width: 100%; background: green; display: flex; justify-content: center; align-items: center; color: white; cursor: pointer; }.option { width: 100%; height: 40px; background: darkgreen; color: white; display: flex; justify-content: center; align-items: center; cursor: pointer; }.option:hover { background: green; }.options { overflow: hidden; transition: max-height 200ms; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <p> {{ selectedCar }}</p> <dropdown v-model="selectedCar" /> </div>
Note there is also tabindex="-1"
to make it not reachable via sequential keyboard navigation.请注意,还有tabindex="-1"
使其无法通过顺序键盘导航访问。
Also consider using a <button>
instead because of accessibility concerns.由于可访问性问题,还考虑使用<button>
代替。
See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex请参阅https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.