【发布时间】:2017-05-15 14:29:04
【问题描述】:
我正在学习 VueJS。我正在弄清楚他们的货币验证example code。
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 调用,触发输入事件。
当我将其注释掉时,实时货币验证不再起作用。所以我意识到它是有目的的。
但是为什么要在输入事件中触发输入事件呢?
你会认为输入事件会再次触发,导致 updateValue 处理程序再次触发,由于递归调用导致堆栈溢出。
我了解 VueJS 更简单的 $emit 示例代码。就像jquery的触发函数一样。
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
// -> "hi"
但在货币验证示例中,我不明白为什么 $emit 以它的使用方式使用,以及它为什么以它的工作方式工作。
谁能解释一下?
【问题讨论】:
-
这种情况下的emit是将事件向上传递到父范围。