Reputation: 929
I'm learning nuxt and the tutor has a function to add an item called updateTodo
and attached it to a button as the follwoing
script
<script setup>
const updateTodo = async (id) => {
if (!input) return;
await $fetch(`/api/todo/${id}`, { method: 'PUT' });
};
</script>
template
<template>
<div class="container">
<input type="text" placeholder="Add a new todo..." v-model="input" />
<NButton @click="() => updateTodo(todo.id)">Add</NButton>
</div>
</template>
I dont know why he didn't call it directly (eg. @click="updateTodo(todo.id)
). I tried to do it and it worked. Is there a reason i dont know or it's just a preference?
Upvotes: 1
Views: 1108
Reputation: 230
<NButton @click="updateTodo(todo.id)">Add</NButton>
a. you call anyFunction in each time, then
<input @input="anyFunction">
b. but you want to pass function if enter value is greater than 100 or anything else then you need to pass as function so you get event as params like
<input @input="(e) => e.target.value > 100 && anyFunction">
In other words, if there is no argument in the function for the particular event then you don't need to pass the function. else you need to pass the function.
Upvotes: 1
Reputation: 1716
Both are allowed.
https://vuejs.org/guide/essentials/event-handling.html#listening-to-events
The usage would be
v-on:click="handler"
or with the shortcut,@click="handler"
. The handler value can be one of the following:
Inline handlers: Inline JavaScript to be executed when the event is triggered (similar to the native onclick attribute).
Method handlers: A property name or path that points to a method defined on the component.
However, note that this isn't necessarily always the case. In some libraries/frameworks, something like onclick="yourFunction()"
might call the method immediately, and use the returned value as an event listener. This is usually not what you want, unless you're returning a function.
Upvotes: 3