在Vue中调用方法时的括号

voi*_*oid 3 javascript vue.js vuejs2

在Vue中,为什么要同时分配侦听器()和不分配侦听器()

new Vue({
  el: "#app",
  data: {
    userName: "Hello World!"
  },
  methods: {
    changeName: function(e){
      this.userName = "Name "+Math.random();
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

<div id="app">
  <p> {{ userName }} </p>
  
  <!-- typing in both the input fields trigger changeName  -->
  
  <input @input="changeName()">
  <input @input="changeName">
  
</div>
Run Code Online (Sandbox Code Playgroud)

在上面的代码段中,两个输入字段上的输入事件都changeName很好地触发,尽管其中一个带有括号,()而一个没有括号。

Jac*_*Goh 7

https://vuejs.org/v2/guide/events.html#Method-Event-Handlers中对此进行了很好的解释。

基本上,事件处理程序可以是

  • 方法名称,例如 @input="changeName"
  • 有效的Javascript语句,例如@input="changeName()"@input="userName = 'Name '+Math.random()"

Vue自动执行检查以检测是哪种情况。

如果您有兴趣,请在https://github.com/vuejs/vue/blob/19552a82a636910f4595937141557305ab5d434e/dist/vue.js#L10086上签出此核心代码。

var handlerCode = isMethodPath
  ? ("return " + (handler.value) + "($event)")
  : isFunctionExpression
    ? ("return (" + (handler.value) + ")($event)")
    : handler.value;
Run Code Online (Sandbox Code Playgroud)


Dav*_* Go 7

确实,这两种情况在 Vue 中都有效。但也有一些区别。

引用:https : //forum.vuejs.org/t/difference-when-calling-a-method-function-with-or-without-brackets/41764/4

@input="改名"

当仅将方法名称绑定为事件处理程序时,事件对象将作为第一个参数传递给事件处理程序。

@input="changeName()"

或者,可以将实际方法调用用作事件处理程序。这允许您将任何自定义参数传递给该方法。