【问题标题】:How to pass a function with arguments via JavaScript object array?如何通过 JavaScript 对象数组传递带参数的函数?
【发布时间】:2016-03-29 06:59:58
【问题描述】:

我有一个项目列表,我想从 JavaScript 数组中提供它的数据:

// HTML
<ul
  <li v-for="menuItem in menuItems">
    <a @click="menuItem.action">{{ menuItem.name }}</a>
  </li>
</ul>

// DATA
data () {
  return {
    menuItems: [
      { name: 'Split up', action: this.split('up') },
      { name: 'Split down', action: this.split('down') },
      { name: 'Split left', action: this.split('left') },
      { name: 'Split right', action: this.split('right') }
    ]
  }

  // METHODS
  methods: {
    split (direction) {
    store.actions.openWindow(direction)
    store.actions.closeMenu()
  }
}

但现在我收到此错误:

[Vue warn]: v-on:click="menuItem.action" expects a function value, got undefined

意思是我错误地传递了action 的值。

正确的做法是什么?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    我不熟悉vue.js,但from the documentationclick 绑定需要一个函数。

    也许您可以尝试以下方法:

    menuItems: [
        // split function and arguments
        { name: 'Split up', action: this.split, arg: 'up' }
        // ...
    ]
    

    然后在你的html中:

    <ul>
      <li v-for="menuItem in menuItems">
        <a @click="menuItem.action(menuItem.arg)">{{ menuItem.name }}</a>
      </li>
    </ul>
    

    或者您也可以尝试以下方法:

    menuItems: [
        // create a new function
        { name: 'Split up', action: function() { return this.split('up') } }
        // ...
    ]
    

    在您的 HTML 中:

    <ul>
      <li v-for="menuItem in menuItems">
        <a @click="menuItem.action()">{{ menuItem.name }}</a>
      </li>
    </ul>
    

    【讨论】:

    • 谢谢。第二个例子只能像这样工作:action: () =&gt; { return this.split('left') }.
    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2020-01-15
    • 2020-09-09
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多