Vue官网技术疑问:为何"value"不能写为"pricevalue"等?否则输入无法转换非数值
Hey Zoe, totally get why this is confusing—let's unpack what's going on here:
Vue’s built-in v-model convention is the culprit
When you usev-modelwith a custom input component (or even native inputs wrapped in a component), Vue has a default rule: it automatically links the component’svalueprop to theinputevent for two-way data sync. If you rename that prop topricevalueor something else, Vue has no idea to use that new name for the v-model binding. So the data stops flowing between parent and component, and your non-numeric conversion logic (which relies on this sync) can’t do its job.You CAN use a custom name—here’s how
If you really want to usepricevalueinstead ofvalue, you just need to tell Vue about your custom convention in the component:export default { // Tell Vue to use our custom prop and event for v-model model: { prop: 'pricevalue', event: 'update:pricevalue' }, // Define our custom prop instead of "value" props: { pricevalue: { type: [Number, String], default: '' } }, methods: { handleInput(e) { // Your non-numeric conversion logic here, e.g., filter out letters const convertedValue = e.target.value.replace(/[^0-9.]/g, '') // Emit the custom event to sync back to parent this.$emit('update:pricevalue', convertedValue) } } }Then in your parent component, you can still use
v-modellike normal:<CustomInput v-model="productPrice" />Why your conversion stops working without this setup
Your conversion logic is probably listening to input changes and updating thevalueprop, or emitting theinputevent with the converted value. When you rename the prop without configuring the custom model, the component doesn’t receive the latest input value from the parent, and the parent doesn’t listen for your converted value—so the input just stays stuck with whatever the user types, no conversion applied.
Quick note: This convention exists to keep component interactions consistent across Vue projects. Everyone expects
v-modelto hook intovalueandinputby default, so deviating requires explicit setup.
内容的提问来源于stack exchange,提问作者Zoe Zhang

