EvonuX
EvonuX

Reputation: 189

Vue - Trying to emit a value as a number and getting string when emitted

The goal is to have a select box when the value is 1-10 and a number input field if it's +10 with a min and max limit as shown in the code.

Changing values with the select works fine and doesn't return errors, however, when changing values on the field it returns a string.

Also trying to make it so that the number can't get below 1 but the field disappears after I add a negative number

<template>
  <div id="app">
    <QuantityInput
      v-on:qtyChange="updateQty($event)"
      :value="input"
      :selectMin="1"
      :selectMax="20"
    />
    <p>Quantity Selected: {{ input }}</p>
  </div>
</template>

<script>
import QuantityInput from "@/components/QuantityInput";

export default {
  name: "App",
  components: {
    QuantityInput
  },
  data() {
    return { input: 1 };
  },
  methods: {
    updateQty(qty) {
      this.input < 1 ? (this.input = 1) : (this.input = qty);
    }
  }
};
</script>

The QuantityInput component

<template>
  <select v-if="qty < 10" v-model="qty" @change="$emit('qtyChange', qty)">
    <option :value="1">1</option>
    <option :value="2">2</option>
    <option :value="3">3</option>
    <option :value="4">4</option>
    <option :value="5">5</option>
    <option :value="6">6</option>
    <option :value="7">7</option>
    <option :value="8">8</option>
    <option :value="9">9</option>
    <option :value="10">10+</option>
  </select>

  <input
    v-else
    type="number"
    :min="selectMin"
    :max="selectMax"
    v-model="qty"
    @change="$emit('qtyChange', qty)"
  />
</template>

<script>
export default {
  name: "QuantityInput",
  props: {
    value: Number,
    selectMin: Number,
    selectMax: Number
  },
  data() {
    return { qty: this.value };
  }
};
</script>

Upvotes: 6

Views: 4361

Answers (2)

Horatius Cocles
Horatius Cocles

Reputation: 141

It looks like you need to use v-bind for establishing a specific data type that's not assumed a string. Here is an example from the Vue.js documentation for props.

Upvotes: 0

EvonuX
EvonuX

Reputation: 189

Making v-model.number did the trick. Thanks to @BrandonPratt !

Upvotes: 8

Related Questions