vue.js - 如何在vuejs中格式化电话(即xxx-xxx-xxxx)标签
问题描述
我想在将电话号码绑定到文本框中时启用文本框进行格式化。
解决方案
鉴于该问题没有太多关于已尝试过什么或如何实现它的信息,我只会制作一个通用组件,供您以后重用。
您可以使用观察者和字段上的正则表达式来执行此操作,将数字格式化为您想要显示的内容
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>
推荐阅读
- mongodb - 如何用 mongodb replace_many 替换_many
- python - 如何从python代码文件为kivy中的小部件设置id
- sql - 雪花 - Dense_rank 从 2 而不是 1 开始
- macos - Crontab 没有按预期运行 python 脚本
- google-apps-script - 在 sheet.appendRow 之后返回附加的行号
- intellij-idea - Intellij Idea,打开新项目为每个项目创建一个新选项卡,如何恢复每个打开项目的默认新窗口?
- anaconda - 将 MiniConda 从 32 位升级到 64 位
- r - 根据少数条件创建新变量
- r - 使用闪亮的R中多列的旭日形图
- reactjs - 无法实现加载器