VUE3 - 格式化 phone 数字的自定义输入。无法在 parent 中使用 v-model
VUE3 - Custom Input to format phone numbers. Can't get to work with v-model in parent
我做了这个自定义输入,基本上接受用户输入和观察,并应用一些正则表达式魔法来格式化 phone 数字。
<template>
<div class="relative flex items-center w-full" style="direction: ltr">
<span class="absolute block ml-3 pointer-events-none">+20</span>
<input
ref="input"
v-model="number"
type="text"
class="w-full border-gray-300 py-2 pr-3 pl-10">
</div>
</template>
<script>
import {ref, watch} from 'vue';
export default {
name: 'XPhoneInput',
setup() {
const number = ref('');
watch(number, () => {
number.value = number.value.replace(/[^0-9]/g, '')
.replace(/^(\d{2})?(\d{4})?(\d{4})?/g, ' ')
.substr(0, 12);
});
return {number};
}
};
</script>
这是 parent
中的标签
<x-phone-input v-model="form.phone" />
我在使用 parent 的 v-model 时遇到了问题。
我在 vue2 中做了一些基本输入,其中 child 组件获取值作为道具并发出更新事件并且当时有效,但我无法在这里工作。或者我想我只是不知道如何让它与观察者一起工作。
我尝试了传递值和发出事件的几种组合。但对我没有任何帮助,我们将不胜感激。
Sami Kuhmonen 指出我做错了什么,没有用 emit 声明道具名称
这是工作代码
export default {
name: 'XPhoneInput',
props: ['modelValue'], //added the prop
emits: ['update:modelValue'], //component emits the updated prop
setup(props, { emit }) {
const number = ref('');
watch(number, () => {
number.value = number.value.replace(/[^0-9]/g, '')
.replace(/^(\d{2})?(\d{4})?(\d{4})?/g, ' ')
.substr(0, 12);
emit('update:modelValue', number.value); //here's what i did wrong, didn't add the prop name to the event name. adding it fixed it. this works
});
return {number};
}
};
我做了这个自定义输入,基本上接受用户输入和观察,并应用一些正则表达式魔法来格式化 phone 数字。
<template>
<div class="relative flex items-center w-full" style="direction: ltr">
<span class="absolute block ml-3 pointer-events-none">+20</span>
<input
ref="input"
v-model="number"
type="text"
class="w-full border-gray-300 py-2 pr-3 pl-10">
</div>
</template>
<script>
import {ref, watch} from 'vue';
export default {
name: 'XPhoneInput',
setup() {
const number = ref('');
watch(number, () => {
number.value = number.value.replace(/[^0-9]/g, '')
.replace(/^(\d{2})?(\d{4})?(\d{4})?/g, ' ')
.substr(0, 12);
});
return {number};
}
};
</script>
这是 parent
中的标签<x-phone-input v-model="form.phone" />
我在使用 parent 的 v-model 时遇到了问题。 我在 vue2 中做了一些基本输入,其中 child 组件获取值作为道具并发出更新事件并且当时有效,但我无法在这里工作。或者我想我只是不知道如何让它与观察者一起工作。 我尝试了传递值和发出事件的几种组合。但对我没有任何帮助,我们将不胜感激。
Sami Kuhmonen 指出我做错了什么,没有用 emit 声明道具名称 这是工作代码
export default {
name: 'XPhoneInput',
props: ['modelValue'], //added the prop
emits: ['update:modelValue'], //component emits the updated prop
setup(props, { emit }) {
const number = ref('');
watch(number, () => {
number.value = number.value.replace(/[^0-9]/g, '')
.replace(/^(\d{2})?(\d{4})?(\d{4})?/g, ' ')
.substr(0, 12);
emit('update:modelValue', number.value); //here's what i did wrong, didn't add the prop name to the event name. adding it fixed it. this works
});
return {number};
}
};