gpt4 book ai didi

javascript - 自定义 vue 组件的模糊事件

转载 作者:行者123 更新时间:2023-12-05 00:30:26 25 4
gpt4 key购买 nike

我有什么
上面带有过滤器文本输入的自定义下拉菜单。 DropDown 可以独立于过滤器文本输入打开。
我想要的
预期的行为是,当过滤器输入失去焦点以及当我在 DropDown 外部用鼠标单击时,下拉菜单关闭,因此 DropDown 失去焦点。
我试过的

  • 绑定(bind)到控件中我的根 div 元素上的 blur 事件,该事件根本不会触发。
  • 我也找不到任何可以覆盖的内部组件方法。

  • 代码
      <div @blur="onRootLostFocus">
    ...
    </div>

    ...
    ...
    ...

    onRootLostFocus() {
    console.log('LostFocus');
    this.deactivateSearchPanel();
    this.deactivateSelectionPanel();
    }
    解决方案
    我错过了,div 需要 tabindex="0"要集中注意力,这解决了我的问题

    最佳答案

    像这样的东西?
    答:需要设置tabindex="0"使其具有焦点。
    这是一个自定义下拉列表,您可以如何做到这一点:

    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>

    关于javascript - 自定义 vue 组件的模糊事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63447804/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com