强制 HtmlButton 失去焦点

Force a HtmlButton to lose focus

我有一个 VueJS 应用程序,其中屏幕上有一个 HTML 按钮,当它被点击时,它是适当的“焦点”,但我想要在短暂延迟后删除焦点的选项。

if (props.defocus === "true" || props.defocus === true) {
  // de-focus the button after 400ms
  setTimeout(() => {
    if (el.value !== null) {
      el.value.blur();
    }
   }, 400);
}

现在我确实提到这是一个 VueJS 项目,但实际上这只是 DOM API 和 JS/TS。我使用 setTimeout 等待 400 毫秒,然后我可以调用按钮上的 blur() 函数。但是,这 not 似乎没有任何作用。现在我想这可能是两件事:

  1. 我已经根据 DOM 成功地移除了按钮元素上的焦点,但是不知何故 VueJS 没有选择它并对它做出反应(也就是,焦点样式仍然存在)
  2. focus() 的调用以某种方式被忽略(没有错误)

有没有办法在开发者工具中检查焦点状态?在获得我正在寻找的行为时,我是否遗漏了什么?

仅供小组中的视觉人士参考,上面的组件是当我单击一个按钮并选中它时,焦点状态由紫色轮廓表示的地方。我希望它在用户单击后消失。

尝试使用指向按钮的指针没有用,但我发现只需查询焦点元素就可以为我提供一个处理程序,我可以在其中调用模糊并让它工作:

if (props.defocus === "true" || props.defocus === true) {
  // de-focus the button after delay
  setTimeout(() => {
    // QUERY FOR FOCUS ELEMENT
    const e2 = document.querySelector(":focus");
    if (e2 && (e2 as HTMLButtonElement).blur) {
      (e2 as HTMLButtonElement).blur();
    }
  }, Number(props.defocusDelay));
}

这没有问题,除非其他人有更好的解决方案,否则我会将其标记为正确的解决方案。

制作指令文件Defocus.ts;

export default {
    name: 'defocus',
    priority: 700,
    bind(el: any, binding: any) {
        el._onClick = () => {
            setTimeout(()=> {
                el.blur();
            }, 400)
        }
        el.addEventListener('click', el._onClick);
    },

    unbind(el: any) {
        el.removeEventListener('click', el._onClick);
    }
};

然后你导入并使用

import Defocus from "@/shared/directives/Defocus";
@Component ({
    directives: {
        Defocus 
    }
})

然后在模板中:

<button v-defocus>Click Me</button>