Josh
Josh

Reputation: 167

Applying a filter to a v-model.number input

I have a table that binds a number of rows to each row's value, not sure how to pipe the value into the filter, which should add 1,000s separators and a currency symbol.

I've successfully used a filter for other values, but I can't get it to work for a v-model input.

<tbody>
<tr v-for="row in rows">
    <td><input v-model.number="row['myValue']" type="number"></td>
</tr>
</tbody>

Vue.filter('toCurrency', function (value) {
    if (typeof value !== "number") { 
    return value;
    } var formatter = new Intl.NumberFormat('en-US', { 
        style: 'currency', 
        currency: firstTable.currencyText, 
        minimumFractionDigits: 0 
    }); 
    return formatter.format(value);
});

Any suggestions would be great.

Upvotes: 0

Views: 1910

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37863

Filters are only intended for applying formatting to values when rendering template - specifically with text interpolation ({{ }}) and v-bind

You can't use filters with 2-way data binding (like v-model) because they are missing the "piece" which takes the formatted value from input and removes the formatting before storing resulting value back into the component's data model.

But v-model is just syntax sugar for updating data on user input events so you can do:

<input
  v-bind:value="row['myValue'] | toCurrency"
  v-on:input="myFunctionWhichRemovesFormattingAndStoreValue($event.target.value, row)"
>

IMHO its much easier to just use component like vue-cleave-component or vue-numeric for that....

Upvotes: 1

Related Questions