How can I set default parameter value in Vue.js method function?

Viewed 10090

I am trying to set a default parameter value for a function in one of my component methods like:

methods: {
    myFuntion(isAction = false) {}
}

But when debug the value of isAction I get a "MouseEvent"?

2 Answers

I found the solution. It looks like the event is also passed to the method by default. Therefore you can set a default parameter value on a method function like:

methods: {
    myFuntion(event, isAction = false) {
        // isAction will be false by default
        // event will have the contain the event object
    }
}
  1. If you call your method like below, it will implicitly pass the event object:
<button @click="myFuntion">Default Action</button>
<!-- isAction will be event -->
  1. If you don't need the event object, just add the parenthesis to the method name:
<button @click="myFuntion()">Default Action</button>
<!-- isAction will be false -->
  1. Otherwise, simply pass the value for isAction:
<button @click="myFuntion(true)">Special Action</button>
<!-- isAction will be true -->
Related