I
I
Ihor Bratukh2019-06-10 23:11:36
JavaScript
Ihor Bratukh, 2019-06-10 23:11:36

How to get selected value of same type in Select Vue component?

There is a wrapper component for select:

<template>
  <select v-on="listeners" :value="value">
    <option v-for="(option, index) of list" :key="index" :value="option">{{ option }}</option>
  </select>
</template>

<script>
export default {
  name: "x-select",

  props: {
    value: {
      type: [Number, String, Boolean],
      required: false,
      default: ""
    },

    list: {
      type: Array,
      required: false,
      default: () => []
    }
  },

  computed: {
    listeners() {
      return {
        ...this.$listeners,
        input: ({ target: { value } }) => this.$emit("input", value)
      };
    }
  }
};
</script>

This component takes the value for $emit from event.target.value. In this property, the value will always be of type string. What if I need to get a value of the type that I put there, that is, from an array list? So, for example, native select works, if you do not use it as a component, how to achieve this effect, where to get the value for $emit from?
How do I use the component:
<template>
  <x-select v-model="selected" :list="list" />
</template>

<script>
export default {
  name: "app",

  data: () => ({
    list: [1, true, "124.5", false, 15.7],
    selected: 1
  })
};
</script>

In this code, after the first selection, the selected property will always be of type string. I can of course use the v-model.number directives to convert to numbers, but that won't help with boolean values. But what if I receive numbers in the number and string types and I don't want to change their type?
This is how native select works and everything is fine here with types:
<template>
  <select v-model="selected">
    <option v-for="(option, index) of list" :key="index" :value="option">
        {{ option }}
    </option>
  </select>
</template>

<script>
export default {
  name: "app",

  data: () => ({
    list: [1, true, "124.5", false, 15.7],
    selected: 1
  })
};
</script>

In this code, the property selectedwill contain exactly the value that is in the array listwith the same type. Tell me how to achieve such a result? Is it possible to parse yourself?
Sandbox:
1. Component wrapper
2. Native select

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-10
@BRAGA96

Use not the values ​​themselves as option values, but their indexes inside the list array. It will be necessary to emit, respectively, list[target.value].
https://jsfiddle.net/krnLyf2q/
Or make a property with a setter inside the computed component (in which $emit will be executed) and use it in v-model.
https://jsfiddle.net/krnLyf2q/1/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question