<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: {
// Instead of updating the value directly, this
// method is used to format and place constraints
// on the input's value
updateValue: function (value) {
var formattedValue = value
// Remove whitespace on either side
.trim()
// Shorten to 2 decimal places
.slice(0, value.indexOf('.') + 3)
// If the value was not already normalized,
// manually override it to conform
if (formattedValue !== value) {
this.$refs.input.value = formattedValue
}
// Emit the number value through the input event
this.$emit('input', Number(formattedValue))
}
}
})
v-on:input="updateValue($event.target.value)" 这个是说,如果发生了input事件,调用updateValue方法,但是方法内部再去this.$emit干嘛。这不是又触发了次input事件吗?然后一直循环下去?
还有,父子组件怎么区分,我看示例也只注册了一个组件呀?
this.$emit()触发的input事件不是组件内部<input>元素的input事件,而是组件根元素<currency-input>的input事件,v-model是一个语法糖,你把
还原为
就知道了,其实它触发的这上面的input事件,实际执行的是setValue方法