Home > Enterprise >  Set Javascript Key Name from Dynamic Prop in Vue 2
Set Javascript Key Name from Dynamic Prop in Vue 2

Time:05-29

I've created my own SelectMenu Vue component that wraps the vue-select package select menu component so that I can get a more streamlined ui flow.

My reusable component looks like so:

<v-select 
  :appendToBody="append"  
  filterable 
  :multiple="multiple"
  :label="label" 
  :placeholder="placeholder" 
  :options="options" 
  :autocomplete="autocomplete" 
  :reduce="option => option.id" 
  @input="selected" 
  v-model="model" />

This works perfectly except when the options key needs to be something other than id

append multiple label placeholder options are all passed into the component as props and I'd like to pass in the option key to use as well.

:reduce="option => option.{passed in key}"

I set a prop called reducer for lack of a better name:

reducer: {
  type: String,
  default: 'id'
}

I tried concatenating it:

:reduce="option => `option.${reducer}`"

But of course this produces a string of "option.id" or whatever the reducer prop is.

How can I set this so it'll be interpreted as javascript?

CodePudding user response:

Have you try using bracket notation to get an object's value by a variable key ? https://bobbyhadz.com/blog/javascript-get-object-value-by-variable-key#:~:text=Use bracket notation to get,get the corresponding value back.&text=Copied!

:reduce="option => option[reducer]"
  • Related