自定义事件也可以用来创建自定义的表单输入组件,使用 v-model 来进行数据双向绑定。
所以要让组件的 v-model 生效,它必须:
- 接受一个 value 属性
- 在有新的 value 时触发 input 事件
代码如下:
HTML:
{{ message }}
Total: ${{ total }}
Javascript:
Vue.component('currency-input', {
template: `
$
`,
props: {
value: {
type: Number,
default: 0
},
label: {
type: String,
default: ''
}
},
mounted: function () {
this.formatValue()
},
methods: {
updatevalue: function (value) {
var result = currencyValidator.parse(value, this.value)
if (result.warning) {
this.$refs.input.value = result.value
}
this.$emit('input', result.value)
},
formatValue: function () {
this.$refs.input.value = currencyValidator.format(this.value)
},
selectAll: function (event) {
setTimeout(function () {
event.target.select()
}, 0)
}
}
})
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
price: 0,
shipping: 0,
handling: 0,
discount: 0
},
computed: {
total: function () {
return ((
this.price * 100 +
this.shipping * 100 +
this.handling * 100 -
this.discount * 10
) / 100).toFixed(2)
}
}
})
效果图如下:
每个 Vue 实例都实现了事件接口(Events interface),即:
使用 $on(eventName) 监听事件
使用 $emit(eventName) 触发事件
v-model实现双向传递。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



