简体   繁体   中英

How to add text to user input - Vue

I have an input where users can enter a price. When the user presses a number key, I want to prepend whatever they type with a '£' sign.

Like this but visible in the input field, not just bound to a data property:

// empty
£1 // first keydown
£12
£125

Example: https://jsfiddle.net/Daniel_Knights/6xn12tj9/6/

Any ideas how to achieve this? Tried a few things but I'm stumped.

Hi Daniel I think you might need to change type="number" to text to allow you to use a non numeric value

This is because you set your input type to number. so you can only use number.

But if you want to force user to enter only number, you can do this:

<div id="app">
  <input type="text" :placeholder="placeholderPrice" v-model="price" @keypress="mustNumber"/>
  <div class="price">
    <p v-if="price !== ''">
    </p>
    {{ price }}
  </div>
</div>
new Vue({
  el: "#app",
  data: {
    price: "£",
  },
  methods: {
        inputPrice(e) {
        this.price = `£${e.target.value}`;
    },
    mustNumber($event) {
            let keyCode = $event.keyCode ? $event.keyCode : $keyCode;

            // only allow number and one dot
            if (
                (keyCode < 48 || keyCode > 57) &&
                (keyCode !== 46)
            ) {
                $event.preventDefault();
            }
        }
  }
})

You need masked input. For example you can use https://vuejs-tips.github.io/v-money/ library

<template>
  <div>
    <money v-model="price" v-bind="money"></money> {{price}}
  </div>
</template>

<script>
  import {Money} from 'v-money'

  export default {
    components: {Money},

    data () {
      return {
        price: 123.45,
        money: {
        decimal: ',',
        thousands: '.',
        prefix: '£ ',
        suffix: '',
        precision: 2,
        masked: false
      }
      }
    }
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM