gpt4 book ai didi

events - 我可以在 svelte 组件上添加条件事件吗?

转载 作者:行者123 更新时间:2023-12-01 21:59:01 25 4
gpt4 key购买 nike

是否可以在父组件中定义的条件下触发事件?

我有一个输入组件,我想在其中捕获输入。有时,但大多数时候我不希望触发该事件

   //App.html
<Input on:inputData="doStuff(event)" fireEvent=true />

//Input.html
<input bind:value=value (fireEvent ? on:keyup='fire("inputData", { value })' : false )/>

目前发生的是 fireEvent 被忽略并且 on:keyup 总是触发

更新
我将 keyup 更改为一个函数调用,我在触发事件之前检查了参数,它有效但有点古怪

//App.html
<Input on:inputData='doStuff(event.value)' fireEvent={true} />
...
methods: {
doStuff(text) {
console.log('here is the stuff', text);
}

//Input.html
<input bind:value=value on:keyup='setData({ value })'/>
...
methods: {
setData(text) {
if(this.get().fireEvent) {
this.fire("inputData", text)
}
}
}

谁有更漂亮的解决方案来解决这个问题?

最佳答案

参加派对已经很晚了,但我遇到了类似的问题并最终通过行动解决了它。对于我来说,只有当某个条件为真时,我才需要将点击监听器附加到按钮。一个更通用的示例可能是:

<button use:conditionalEvent({condition: foo, event: 'click', callback: bar})>...</button>

...

function conditionalEvent(node, {condition, event, callback}) {
if (condition) {
node.addEventListener(event, callback);
}

return {
destroy() {
node.removeEventListener(event, callback)
}
}
}

如果仅针对单个回调或事件类型,则标记可能不那么冗长,但您明白了。如果条件可以随着用户输入而改变,你也可以返回一个更新函数:

function changingCondition(node, {condition, event, callback}) {
function update(condition) {
if (condition) {
node.addEventListener(event, callback);
} else {
node.removeEventListener(event, callback);
}
}

update(condition);

return {
update,
destroy() {
node.removeEventListener(event, callback)
}
}
}

只要 condition 发生变化,更新就会运行。

关于events - 我可以在 svelte 组件上添加条件事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54464655/

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