Home > Software engineering >  What's the difference in Vue @click between calling a method directly and calling in inside a f
What's the difference in Vue @click between calling a method directly and calling in inside a f

Time:06-24

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 >
    <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?

CodePudding user response:

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:

  1. Inline handlers: Inline JavaScript to be executed when the event is triggered (similar to the native onclick attribute).

  2. 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.

CodePudding user response:

  1. in this case you call directly, you don't require event parmas here.
<NButton @click="updateTodo(todo.id)">Add</NButton>
  1. but in a certain case, you need event parament to get the value of the input (e.target.value) or want to prevent the default of that event(e.preventDefault) i.e

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.

  • Related