如何通过 JavaScript 对象数组传递带参数的函数?

How to pass a function with arguments via JavaScript object array?

我有一个项目列表,我想从 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 的值。

正确的做法是什么?

我不熟悉 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>