docs icon indicating copy to clipboard operation
docs copied to clipboard

`v-on` modifier `.once` triggers handler at most once... per what?

Open nekomachi-touge opened this issue 1 year ago • 5 comments

https://github.com/vuejs/docs/blob/a961225c9dbfde52c510ce19549a74eb34993bea/src/api/built-in-directives.md?plain=1#L187

I found the statement above unclear, because this could imply the listener would be called once per:

  • an event,
  • a mount,
  • an update or
  • a span in lifecycle (possibly specified somewhere).

This could lead readers to assume the semantics or simply avoid using this modifier not to cause confusion.

nekomachi-touge avatar Sep 20 '24 11:09 nekomachi-touge

@nekomachi-touge The confusion about "mount," "update," or "lifecycle" phases doesn't apply directly here. The .once modifier is strictly tied to the event listener itself, not the component lifecycle. So, if the listener is attached to an event like @click/@change/@input etc., it will trigger once when the event occurs and then be removed.

<template>
  <button @click.once="handleClick">Click Me</button>
</template>

<script setup>
function handleClick() {
  console.log('Button clicked');
}
</script>

In this case, the handleClick function will only run once, regardless of how many times the button is clicked, because the event listener is removed after the first trigger.

Note: check line docs/src/api/built-in-directives.md#178 for the Argument.

mahmudunnabikajal avatar Sep 28 '24 14:09 mahmudunnabikajal

@mahmudunnabikajal Umm, I found your argument doesn't clarify when a listener is (re)set, even though it happens independent of the lifecycle. I don't expect a listener will run really once, like persisting with user agent's navigation (e.g. future revisits will not invoke the listener, by saving its state in Cookie, IndexedDB or something).

nekomachi-touge avatar Oct 09 '24 11:10 nekomachi-touge

@mahmudunnabikajal Umm, I found your argument doesn't clarify when a listener is (re)set, even though it happens independent of the lifecycle. I don't expect a listener will run really once, like persisting with user agent's navigation (e.g. future revisits will not invoke the listener, by saving its state in Cookie, IndexedDB or something).

@nekomachi-touge The use case varies for each individual. I suggest creating a custom directive tailored to your specific requirements

mahmudunnabikajal avatar Oct 09 '24 11:10 mahmudunnabikajal

@mahmudunnabikajal Maybe there is a misunderstanding. What I want to achieve here is to clearly state (or make it obvious) when a listener with the modifier is set/invokable.

nekomachi-touge avatar Oct 09 '24 13:10 nekomachi-touge

Maybe there is a misunderstanding. What I want to achieve here is to clearly state (or make it obvious) when a listener with the modifier is set/invokable.

I understand your issue. It will review by a admin. Thanks :heart:

mahmudunnabikajal avatar Oct 09 '24 13:10 mahmudunnabikajal