【问题标题】:How can I set default parameter value in Vue.js method function?如何在 Vue.js 方法函数中设置默认参数值?
【发布时间】:2019-11-02 12:46:44
【问题描述】:

我正在尝试在我的组件方法之一中为函数设置默认参数值,例如:

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

但是当调试 isAction 的值时,我得到一个“MouseEvent”?

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    我找到了解决方案。看起来事件也默认传递给方法。因此,您可以在方法函数上设置默认参数值,例如:

    methods: {
        myFuntion(event, isAction = false) {
            // isAction will be false by default
            // event will have the contain the event object
        }
    }
    

    【讨论】:

    • Nit:默认值是现代 JavaScript 语法,所以放弃旧的 function 并使用:myFuntion(event, isAction = false) {
    【解决方案2】:
    1. 如果您像下面这样调用您的方法,它将隐式传递事件对象:
    <button @click="myFuntion">Default Action</button>
    <!-- isAction will be event -->
    
    1. 如果您不需要事件对象,只需在方法名称中添加括号
    <button @click="myFuntion()">Default Action</button>
    <!-- isAction will be false -->
    
    1. 否则,只需传递 isAction 的值:
    <button @click="myFuntion(true)">Special Action</button>
    <!-- isAction will be true -->
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-05
      • 2010-10-22
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      相关资源
      最近更新 更多