export default {
inheritAttrs: false,
model: { event: 'filtered' },
props: {
value: { default: '' },
},
data() {
return {
oldFormattedValue: '' // 保存上一个格式化值
}
},
computed: {
innerValue: {
get() {
return this.value.replace(/\D/g, '').replace(/(\d{4})(?=\d)/g, '$1 ')
},
set(value) {
const newValue = value.replace(/\D/g, '');
this.$emit('filtered', newValue);
this.adjustCursorPosition(newValue);
this.oldFormattedValue = this.innerValue;
}
}
},
methods: {
adjustCursorPosition(newValue) {
const input = this.$refs.inputField.$el.querySelector('input');
const oldPos = input.selectionStart;
// 计算旧格式化值和新格式化值之间的差异
const oldFormattedValueDiff = this.oldFormattedValue.slice(0, oldPos).split(' ').length - 1;
const newFormattedValueDiff = this.innerValue.slice(0, oldPos + oldFormattedValueDiff).split(' ').length - 1;
const diff = newFormattedValueDiff - oldFormattedValueDiff;
// 调整光标位置
const newPos = oldPos + diff;
input.setSelectionRange(newPos, newPos);
}
}
}