首页 > 解决方案 > 如何在vuejs中格式化电话(即xxx-xxx-xxxx)标签

问题描述

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

标签: vue.jsvuejs2vue-componentvuex

解决方案


鉴于该问题没有太多关于已尝试过什么或如何实现它的信息,我只会制作一个通用组件,供您以后重用。

您可以使用观察者和字段上的正则表达式来执行此操作,将数字格式化为您想要显示的内容

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'
});
<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>


推荐阅读