LoginSignup
5
3

More than 3 years have passed since last update.

v-modelにフィルタをかける

Last updated at Posted at 2019-03-03

v-model以外はフィルターを使えば困らなかったけどv-modelの場合に困った。

v1ではTwo-way-フィルタがあったがv2では無い。

Two-Way フィルタ 置き換え

https://jsfiddle.net/chrisvfritz/1oqjojjx/?utm_source=website&utm_medium=embed&utm_campaign=1oqjojjx

入力欄に価格を入れてカンマ表示を行う例

computedのsetとgetでもできましたが整形後のdataに変更がない場合はキャッシュが使用され調整しないとうまくいかなかったです。


Vue.component('currency-input', {
    template: '\
        <input\
            type="text"\
            name="name"\
            v-bind:name="name"\
            ref="input"\
            v-bind:value="value"\
            v-on:input="updateValue($event.target.value)"\
            v-on:focus="selectAll"\
            v-on:blur="formatValue"\
        >\
    ',
    props: {
        name: {
            type: String,
            default: ''
        },
        value: {
            type: String,
            default: ''
        }
    },
    mounted: function () {
        this.formatValue()
    },
    methods: {
        updateValue: function (value) {
            let formatValue = parseInt(value.replace( /[^0-9\-]/g, ''), 10);
            if (isNaN(formatValue)) {
              formatValue = 0;
            }
            formatValue = 
formatValue.toString().replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
            this.$refs.input.value = formatValue;
            this.$emit('input', formatValue);
        },
        formatValue: function () {
            let formatValue = parseInt(this.value.replace( /[^0-9\-]/g, ''), 10);
            if (isNaN(formatValue)) {
              formatValue = 0;
            }
            this.$refs.input.value = formatValue.toString().replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
        },
        selectAll: function (event) {
            // Workaround for Safari bug
            setTimeout(function () {
                event.target.select();
            }, 0)
        }
    }
});

new Vue({
    el: '#price',
    data: {
      price1 : '0',
      price2 : '0',
    }
});


<div id="price">
<currency-input name="test[0]" v-model="price1"></currency-input>
<currency-input name="test[1]" v-model="price2"></currency-input>
</div>

追記

:value="A | フィルタ"
@input="Aをフィルタ前の値に戻すmethod"

の方が簡単にできそうな気がした。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3