Home >Web Front-end >JS Tutorial >Form input component method of Vue.js custom event
Below I will share with you a form input component method for Vue.js custom events. It has a good reference value and I hope it will be helpful to everyone.
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: --Use binding v- when referencing the child component template in the parent component 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)) } } })
Custom component’s v-model
2.2.0 Added
By default, a component’s v-model Will use value prop and input events. But input types such as radio buttons and check boxes 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.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
A brief discussion on React high-order components
vue-cli axios request method and cross-domain processing issues
The above is the detailed content of Form input component method of Vue.js custom event. For more information, please follow other related articles on the PHP Chinese website!