如何使用 <b-input > 标签在 vuejs 中格式化电话(即 xxx-xxx-xxxx)

Bha*_*tap 3 vue.js vue-component vuex vuejs2

我想在将电话号码绑定到文本框中时启用文本框进行格式化。

Ale*_*les 5

鉴于这个问题没有太多关于已尝试过的内容或如何实现它的信息,我将制作一个您可以稍后重用的通用组件。

您可以使用观察器和字段上的正则表达式来将数字格式化为您想要显示的内容

Vue.component('my-phone-input', {
    template: `
        <div>
            <input type="text" v-model="formattedPhoneValue" @keyup="focusOut" @blur="focusOut"/>
        </div>`,
    data: function() {
        return {
            phoneValue: 0,
            formattedPhoneValue: "0",
            preventNextIteration: false
        }
    },
    methods: {
        focusOut: function(event) {
            if (['Arrow', 'Backspace', 'Shift'].includes(event.key)) {
            		this.preventNextIteration = true;
                return;
            }
            if (this.preventNextIteration) {
		            this.preventNextIteration = false;
            		return;
            }
            this.phoneValue = this.formattedPhoneValue.replace(/-/g, '').match(/(\d{1,10})/g)[0];

						// Format display value based on calculated currencyValue
            this.formattedPhoneValue = this.phoneValue.replace(/(\d{1,3})(\d{1,3})(\d{1,4})/g, '$1-$2-$3');
        }
    }
});

new Vue({
    el: '#app'
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
    <my-phone-input></my-phone-input>
</div>
Run Code Online (Sandbox Code Playgroud)