简体   繁体   English

在 vue.js 中从 html 调用 function 时花括号

[英]Curly braces when calling a function from html in vue js

when calling function, for example on click it doesn't matter if I write curly braces or not.当调用 function 时,例如单击时,我是否写花括号并不重要。 It works in both scenarios.它适用于两种情况。 But I made a function, which fires custom event from a child.但是我做了一个 function,它触发了一个孩子的自定义事件。 then I await it in a parent component and fire my function (which is in parent), to update state. I noticed when I write curly braces on that function, vue returns an error.然后我在父组件中等待它并触发我的 function(在父组件中)以更新 state。我注意到当我在 function 上写花括号时,vue 返回错误。 why is that happening?为什么会这样? (I'm new to vue.js:) ). (我是 vue.js 的新手:))。

function in a child component, which is invoked on click:子组件中的 function,点击时调用:

  toggleFavorite: function () {
          this.$emit("toggle-favorite", this.id);
        }

A child component rendered inside a parent在父组件中呈现的子组件

<friend-contact
      v-for="friend in friends"
      :data="friend"
      :key="friend.id"
      @toggle-favorite="toggleFavorite"> // if i write 'toggleFavorite()' here, I am 
                                         // geting an error
                                         
    </friend-contact>

A function which is fired on custom event在自定义事件上触发的 function

 toggleFavorite: function (id) {
      let friendToUpdate = this.friends.find((el) => el.id === id);
      friendToUpdate.favorite = !friendToUpdate.favorite;
    }

An event doesn't matter, what matters here is whether a parameter is used in event handler or not.事件无关紧要,这里重要的是事件处理程序中是否使用了参数。

@toggle-favorite="toggleFavorite" results in toggleFavorite being used as event handler. @toggle-favorite="toggleFavorite"导致toggleFavorite被用作事件处理程序。

@toggle-favorite="toggleFavorite()" results in toggleFavorite() expression being evaluated on event, with id parameter being undefined . @toggle-favorite="toggleFavorite()"导致在事件上评估toggleFavorite()表达式,其中id参数为undefined

There is $event magic value that represents event parameter in event handler. $event魔法值表示事件处理程序中的事件参数。 In order to match the first syntax, it should be @toggle-favorite="toggleFavorite($event)" .为了匹配第一个语法,它应该是@toggle-favorite="toggleFavorite($event)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM