Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue $emit passing argument to a function that already have arguments

I have this in my component:

template: <input @blur="$emit('customEvent', arg1)" v-model="arg1">

And this in my html template:

<component @customEvent="method1(arg2)"></component>

I need to provide a parameter (arg2) to the method1() function, but also I need to get the arg1 from $emit().

I tried this (into the Vue instance):

method1(arg2, arg1) {
      console.log("This is the arg2: " + arg2);
      console.log("This is the arg1: " + arg1);
    }

Of course, I tried to reverse them, not working, the arg1is not getting passed, but replaced.

I know it must have a namespace (perhaps something like arg1=arg1), but I haven't found anything like this.

like image 763
yierstem Avatar asked Apr 09 '18 09:04

yierstem


1 Answers

It can work by passing $event into the methods.

$event will be the payload you pass in the emit function. When you do $emit('customEvent', arg1), arg1 will be passed as $event to @customEvent.

<component @customEvent="method1($event, arg2)"></component>

and in methods:

method1(arg1, arg2) {
  console.log("This is the arg2: " + arg2);
  console.log("This is the arg1: " + arg1);
}

proof of concept: https://jsfiddle.net/jacobgoh101/e8a5k3ph/1/


alternative solution:

<component @customEvent="(eventPayload) => method1(eventPayload, arg2)"></component>
like image 110
Jacob Goh Avatar answered Nov 14 '22 20:11

Jacob Goh