gpt4 book ai didi

typescript - 将属性添加到 HtmlElement

转载 作者:行者123 更新时间:2023-12-02 19:06:22 26 4
gpt4 key购买 nike

[[WARNING]]:看起来像问题 TypeScript: add type property to HtmlElement但我需要向元素对象添加一个函数,而不是向节点添加属性。

我尝试将 JavaScript 转换为 TypeScript 但我是 TypeScript 的新手,我尝试添加一个新的el.clickOutsideEvent 函数,但 ts 不允许我这样做:

Vue.directive('click-outside', {
bind: function (el: HTMLElement, binding: Object, vnode: VNode) {
// stack-overflow: https://stackoverflow.com/a/42389266/13031497
el.clickOutsideEvent = function (event: MouseEvent): void {
if (!(el == event.target) ||
event.target instanceof Node && el.contains(event.target)) {
vnode.context[binding.expression](event);
}
}
// ugly, but fix the bug:
// 2020/11/20 - Peterlits Zo
// When I click the the ellipsis-h buttom, it do not change anything.
// I find that itself call this function auto, so I add this after times.
setTimeout(() => {
document.body.addEventListener('click', el.clickOutsideEvent)
}, 50)
},
unbind: function (el: HTMLElement) {
document.body.removeEventListener('click', el.clickOutsideEvent)
},
})

它告诉我:属性“clickOutsideEvent”在类型“HTMLElement”上不存在。和其他内容。

我应该为它做什么?

最佳答案

我会创建一个从 HTMLElement 扩展的自定义界面。

interface IHTMLElementClicketyClick extends HTMLElement {
clickOutsideEvent?(event: MouseEvent): void;
}

Vue.directive('click-outside', {
bind: function (el: IHTMLElementClicketyClick, binding: Object, vnode: VNode) {

// the rest of the code

关于typescript - 将属性添加到 HtmlElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65005656/

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