自定义事件也可以用来创建自定义的表单输入组件,使用 v-model
来进行数据双向绑定。牢记:
<input v-model="something">
仅仅是一个语法糖:
<input v-bind:value="something" v-on:input="something = $event.target.value">
所以在组件中使用时,它相当于下面的简写:
<input v-bind:value="something" v-on:input="something = arguments[0]">
所以要让组件的 v-model
生效,它必须:
- 接受一个 value 属性
- 在有新的 value 时触发 input 事件
一个非常简单的货币输入:
HTML代码:
<currency-input v-model="price"></currency-input>
JS代码:
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))
}
}
})