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

落爺英雄遲暮 提交于 2019-12-25 01:14:24

问题


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

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

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


回答1:


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



回答2:


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: function(event, isAction = false) {
        // isAction will be false by default
        // event will have the contain the event object
    }
}


来源:https://stackoverflow.com/questions/56673411/how-can-i-set-default-parameter-value-in-vue-js-method-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!