我在学VueJS.我正在计算他们的货币有效性.
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('.') === -1
? value.length
: 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))
}
}
})
updateValue函数底部的$emit调用触发一个输入事件.
当我把它 comments 出来时,实时货币验证不再有效.所以我意识到这是有目的的.
但为什么要在输入事件中触发输入事件呢?
您可能认为输入事件会再次触发,导致updateValue处理程序再次触发,导致递归调用导致堆栈溢出.
我理解VueJS的简单得多的$emit示例代码.这就像Jquery的触发器函数一样.
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
// -> "hi"
但是在货币验证的例子中,我不明白为什么$emit是这样使用的,为什么它是这样工作的.
有人能解释一下吗?