特别声明:如果您喜欢小站的内容,可以点击申请会员进行全站阅读。如果您对付费阅读有任何建议或想法,欢迎发送邮件至: airenliao@gmail.com!或添加QQ:874472854(^_^)
上一节中,通过v-model
的学习,我们可以实现双向数据绑定的的效果。在整个教程中,我们看到的示例都是表单控件方面的。实际上v-model
还可以和组件结合在一起实现双向数据的绑定效果。
在Web的表单控件中,我们经常为了一些特殊的视觉效果,做自定义的表单风格,比如单选按钮、复选框和下拉选择框之类的。那么我们通过Vue来做这些表单控件的组件,会让我们变得更为轻松,而且一劳永逸。接下来我们看看怎么实现单选按钮和复选框的组件。
自定义单选按钮
与复选框相比,定制单选安扭相对而言要简单。以下是一个非常基本的自定义单选按钮。将input
和label
包装在标签中。下面这个示例是来自@Invoke的Vue单选按钮。
我们把整个Demo写在Codepen上,以便大家更为方便的查阅代码。
创建radio
组件,代码如下:
Vue.component('radio',{
template: `
<div class="custom-radio" v-bind:class="{ inverted: inverted }">
<input type="radio" v-bind:name="name" v-bind:class="className" v-bind:id="id" v-bind:checked="checked" v-bind:value="value" v-bind:required="required" v-on:change="updateInput" />
<label v-bind:for="id">{{ label }}</label>
</div>
`,
props: {
name: {
type: String,
required: false
},
className: {
type: String,
required: false
},
id: {
type: String,
required: false
},
value: {
type: String,
required: false
},
required: {
type: Boolean,
required: false,
default: false
},
checked: {
type: Boolean,
required: false,
default: false
},
label: {
type: String,
required: true
},
inverted: {
type: Boolean,
required: false,
default: false
}
},
methods: {
updateInput: function(event) {
this.$emit('input', event.target.value);
}
}
})
通过Vue.component()
创建了一个radio
组件,同时把组件需要的模板(HTML)结构定义在template
中:
<div class="custom-radio" v-bind:class="{ inverted: inverted }">
<input type="radio" v-bind:name="name" v-bind:class="className" v-bind:id="
如需转载,烦请注明出处:https://www.w3cplus.com/vue/custom-radio-and-checkbox-component-with-vue.html
如果文章中有不对之处,烦请各位大神拍正。如果你觉得这篇文章对你有所帮助,打个赏,让我有更大的动力去创作。(^_^)。看完了?还不过瘾?点击向作者提问!