Adding custom parameter(s) to function call bound to component in VueJS

Viewed 789

Problem

While binding a function to a component in VueJS, I'm trying to pass in custom parameter(s), and also accept the parameter(s) supplied by that component to the same function.

Context

I'm adding a custom sort function to a Bootstrap-Vue table.

When calling this function, the table component passes 7 parameters into it.

My complication is that in order to sort a certain column, I need information from the outer scope, and so I want to dynamically pass that needed information into the sort function directly in the v-bind property. This is fine, except I can't figure out how to both pass in my custom parameter as well as accept the 7 parameters provided when Bootstrap-Vue calls my function internally.

Eg. I can call it like this:

<b-table :sort-compare="sortTable" />

And get access to all 7 parameters in sortTable().

But if I add my own to the list:

<b-table :sort-compare="sortTable(myData)" />

I only have my one parameter instead, and the other 7 are lost.

Tried passing in ...arguments, but that doesn't do what I want either.

Question

Is this possible? Is there a special Vue instance $[property] to use as a placeholder in bound function calls, like $event for event listeners, that I've missed?

1 Answers

The easiest option here is to create a new function.

You can use an inline arrow function like this

<b-table :sort-compare="(...args) => sortTable(myData, ...args)" />
methods: {
  sortTable(data, a, b, key, desc, formatter, options, locale) {
    // do what you gotta do
  }
}

Of course, this can get pretty messy so you could use a method to create the function

<b-table :sort-compare="createSortCompare(myData)" />
methods: {
  createSortCompare(data) {
    return (a, b, key, desc, formatter, options, locale) => {
      // you now have access to all arguments as well as "data"
    }
  }
}
Related