问题
我有一个v-phone
指令,用于格式化表单输入的值。问题在于它在v-for
指令中不起作用。可以补救吗?应该将其重构为组件吗?
代码
<template v-for="(user in record.users">
<!-- ... -->
<input v-model="user.phone" v-phone="user.phone" type="text" />
<!-- ... -->
</template>
Vue.directive('phone', (el, binding, vnode) => {
let characters = _.split(binding.value, '');
let cleanCharacters = _.filter(characters, character => is.alphaNumeric(character));
let cleanValue = _.join(cleanCharacters, '');
let formattedValue = cleanValue.replace(/(\d{3})(\d{3})(\d{4})([a-z0-9])?/, '$1-$2-$3 $4');
if (_.trim(binding.oldValue) === _.trim(formattedValue)) return;
_.set(vnode.context, binding.expression, formattedValue);
});
环境
答案 0 :(得分:1)
我遇到了同样的问题(在“ vue”中:“ ^ 2.5.2”),但是使用它来解决此问题:
mounted(){
this.$nextTick(function () {
//to fix v-for
let _this=this;
setTimeout(function () {
_this.$forceUpdate()
},20)
})
希望有帮助