vue.js - vue 基础教程疑问
本文介绍了vue.js - vue 基础教程疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<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是一个语法糖,你把
<currency-input v-model="price"></currency-input>`
还原为
<currency-input v-bind:value="price" v-on:input="setValue"></currency-input>
methods: {
setValue(value) {
this.price = value
}
}
就知道了,其实它触发的这上面的input事件,实际执行的是setValue方法
这篇关于vue.js - vue 基础教程疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文