Home >Web Front-end >JS Tutorial >How to use Vue.js custom events for form input components
This time I will show you how to use Vue.js custom events to implement form input components. What are the precautions for using Vue.js custom events to implement form input components. Here are practical cases. Let’s take a look. take a look.
Vue.js forms input components using custom events
Custom events can be used to create custom form input components and use v-model to process data Two-way binding. Something to keep in mind:
<input v-model="something">
This is just syntactic sugar for the following example:
<input v-bind:value="something" v-on:input="something = $event.target.value">
So when used in a component, it is equivalent to the shorthand for:
<custom-input v-bind:value="something" v-on:input="something = arguments[0]"> </custom-input>
So for the v-model of the component to take effect, it should (configurable from 2.2.0 onwards):
Accepts a value prop
In The input event is triggered when there is a new value and the new value is used as a parameter
Let's look at a very simple custom control for currency input:--Refer to the child component template in the parent component When binding v-model data:
<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: { // 不是直接更新值,而是使用此方法来对输入值进行格式化和位数限制 updateValue: function (value) { var formattedValue = value // 删除两侧的空格符 .trim() // 保留 2 位小数 .slice( 0, value.indexOf('.') === -1 ? value.length : value.indexOf('.') + 3 ) // 如果值尚不合规,则手动覆盖为合规的值 if (formattedValue !== value) { this.$refs.input.value = formattedValue } // 通过 input 事件带出数值 this.$emit('input', Number(formattedValue)) } } })
Selfdefine component v-model
2.2.0 New
By default, a component's v-model will use value prop and input events. But input types such as radio buttons and checkboxes may use value for other purposes. The model option can avoid such conflicts:
Vue.component('my-checkbox', { model: { prop: 'checked', event: 'change' }, props: { checked: Boolean, // 这样就允许拿 `value` 这个 prop 做其它事了 value: String }, // ... })
<my-checkbox v-model="foo" value="some value"></my-checkbox>
The above code is equivalent to:
<my-checkbox :checked="foo" @change="val => { foo = val }" value="some value"> </my-checkbox>
Note that you still need to explicitly declare the checked prop.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
vue-router does not display routes when building How to deal with the page
The above is the detailed content of How to use Vue.js custom events for form input components. For more information, please follow other related articles on the PHP Chinese website!