1.实现input格式化
<template>
<input
type="text"
@input="strFormat($event.target)"
>
</template>
<script>
export default {
data: () => ({
phone: ''
}),
methods: {
strFormat(target) {
// 对未格式化的数据做保存,用来提交验证
this.phone = target.value.toString().replace(/\s/g, '')
target.value = this.formatPhone(this.phone, [3, 7])
},
// 格式处理,按照传入的位置添加空格
formatPhone(value, termArray) {
let ret = Array.from(value)
termArray.map((item, index) => {
const newIndex = item + index
if (ret.length > newIndex) {
const target = ret[newIndex]
ret.splice(newIndex, 0, ' ')
}
})
return ret.join('')
}
}
}
</script>