Use Vue prop as part of function declaration

90 Views Asked by At

I use vue-select in my Vue app. I created a component as a wrapper for v-select. To return only a specific column of the options array, I use the :reduce prop of vue-select.

<template>
<span>
    <label v-if="title">{{title}}</label>
    <v-select
        :options="options"
        :label="label"
        :placeholder="placeholderText"
        :close-on-select="closeOnSelectValue"
        :disabled="isDisabled"
        :multiple="multiple"
        :value="value"
        @input="handleInput($event)"
        :loading="isLoading"
        :reduce="option=> option.val"
    ></v-select>
</span>

This code works, but I would like to have the static val string to be the dynamic prop returnKey. This would be passed to the component as a prop.

props: {
        returnKey: {
            type: String,
            default: null,
        },
}

What syntax should I use to make a combination of the 'option' string and the dynamic value of 'returnKey' in the function passed to :reduce to get this working?

2

There are 2 best solutions below

1
On BEST ANSWER

You can use the bracket notation and do option => option[returnKey].

And as what Richard has suggested, in order to avoid runtime error you might want to provide some kind of fallback, or enforce that returnKey must be a required prop.

0
On

You can try something like this

<template>
<span>
    <label v-if="title">{{title}}</label>
    <v-select
        :options="options"
        :label="label"
        :placeholder="placeholderText"
        :close-on-select="closeOnSelectValue"
        :disabled="isDisabled"
        :multiple="multiple"
        :value="value"
        @input="handleInput($event)"
        :loading="isLoading"
        :reduce="reduceKey"
    ></v-select>
</span>
</template>

<script>
export default
{
  props: {
        returnKey: {
            type: String,
            default: null,
        },
  },
  methods:
  {
    reduceKey(option)
    {
      return option[this.returnKey] || option;
    }
  }
}