<currency-input v-model="price"></currency-input>
Vue.component('currency-input', {
template: '\
<span>\
$\
<input\
ref="input"\
v-bind:value="value"\
v-on:input="updateValue($event.target.value)"\
>\
</span>\
',
props: ['value'],
methods: {
// 不是直接更新值,而是使用此方法来对输入值进行格式化和位数限制
updateValue: function (value) {
var formattedValue = value
// 删除两侧的空格符
.trim()
// 保留 2 小数位
.slice(0, value.indexOf('.') + 3)
// 如果值不统一,手动覆盖以保持一致
if (formattedValue !== value) {
this.$refs.input.value = formattedValue
}
// 通过 input 事件发出数值
this.$emit('input', Number(formattedValue))
}
}
})
vue入门指导里的,请问input事件是什么时候触发的,一旦触发,`this.$emit('input', Number(formattedValue))`不会导致input事件不停被触发,updateValue循环被调用吗?
So input is triggered when the content in input changes. As for
this.$emit('input', Number(formattedValue))
, in fact, the custom event 'input' is sent here. He uses It is for the communication between parent and child components, which means that theemit
event here will not be captured by the component itself, that is, it will not trigger theupdateValue
here. Your<currency-input v-model= "price"></currency-input>
Add the monitoring ofinput
here,emit
is triggered here, so the loop call you mentioned will not be sent.