Search code examples
vue.jsevent-handling

Vuejs. is it possible to pass a function returned from another function to event handler?


<template>
  <v-list-item v-for="(category, i) in categories" :key="i">
    <v-item-group multiple @update:model-value="selectedChanged(category)">
       <v-item></v-item>
    </v-item-group>
  </v-list-item>
</template>

<script>
  function selectedChanged(category) {
    return function(items) {
      console.log(`select ${items} from ${category}`);
    }
  }
</script>

I hope that, in function selectedChanged, I can know which category was selected. But it doesn't work. Vue just called selectedChanged with parameter category.

The reason why I want to do this is that, if I define selectedChanged as follows:

function selectedChanged(items) {
  console.log(items);
}

I don't know which category was selected.

How to impelement function selectedChanged so that I can know which category was selected?


Solution

  • Like Estus said in the comments, it looks like what you want can probably be achieved by explicitly passing $event as one of your event handler arguments. (Here is a link to the relevant Vue 3 documentation on $event.) The code would look something like this:

    <template>
      <v-list-item v-for="(category, i) in categories" :key="i">
        <v-item-group multiple @update:model-value="selectedChanged(category, $event)">
           <v-item></v-item>
        </v-item-group>
      </v-list-item>
    </template>
    
    <script>
      function selectedChanged(category, items) {
        console.log(`select ${items} from ${category}`);
      }
    </script>
    

    Of course, this solution assumes that the items you're looking for are emitted by the update:model-value call in (what I assume to be) Vuetify. You might need to do some destructuring or refactoring to get precisely what you want.