Home > OS >  Can I return a function from methods property in Vue and use it as event handler?
Can I return a function from methods property in Vue and use it as event handler?

Time:06-15

Can we do something like this in Vue or I have to use only arrow function.

<template>
<vue-component
 v-for="(data, index) in someArr"
 @someEvent="someMethodWrapper(data)" 
>
</vue-component>
</template>

<script>
 methods: {
  someMethodWrapper(data) {
   return (someotherData) => {
    this.setNewProperty = { [data]: someOtherData }
   }
  }
 }
</script>

CodePudding user response:

v-on binding can accept either a function or an expression as event handler. A function that an expression evaluates to won't be used as event handler in this case.

This code just executes someMethodWrapper and ignores a function it returns. It could be workable by explicitly calling it:

@someEvent="someMethodWrapper(data)($event)" 

At this point it doesn't serve a good purpose to make someMethodWrapper higher order function, it could change signature to fit the case better:

someMethodWrapper(someotherData, data) {...}

and

@someEvent="someMethodWrapper($event, data)" 
  • Related