N
N
Nikolai Chuprik2020-02-16 01:30:20
Vue.js
Nikolai Chuprik, 2020-02-16 01:30:20

How to format price value in input associated with numerical value using v-model?

There is an input with a price, it is connected in a numeric variable. I want to make it so that while the input does not have focus, the content is formatted: "12 345 rubles", and as soon as the input has input focus, the formatting is canceled: "12345". After the end of input (loss of focus), the formatting returned. To format the price, I have the Number.rub() method, which does this
<input v-model = "price">


price = 12345;
console.log( price.rub() );     // 12 345 руб.


The question is how to do this formatting?

UPD: I used to do this
<input 
   v-model = "price"
   @focus = "price = price._rub()"
   @blur = "price = price.rub()"
>

where _rub() converts the formatted price (from the string) back to a number. But, you see, this method is a complete crap, because. the type of the price variable changes back and forth.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-02-16
@choupa

Make two different (really, of course, it will be the same) inputs that will be switched with v-if/ v-else- one to show the formatted value, the other to edit:

<input v-if="edit" v-model="price" @blur="edit = false">
<input v-else :value="formatPrice(price)" @focus="edit = true">

data: () => ({
  edit: false,
  price: 666,
}),
methods: {
  formatPrice: price => `${(+price).toLocaleString()} руб.`,
},

https://jsfiddle.net/j6tf20cg/UPD
. You can get by with one, but without v-model .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question