实现表单组件 #
- 组件结构目录
├── App.vue ├── components │ ├── Form.vue │ ├── FormItem.vue │ └── Input.vue └── package.json
表单组件的使用 #
- Form 提供组件的数据
- FormItem 实现表单校验功能
- Input 输入内容时让FormItem发生校验
使用组件的方式 #
Form组件的基本结构 #
FormItem组件结构 #
校验文字
Input组件结构 #
实现组件间的数据传递 #
- 为了在formItem中可以拿到form组件中的数据
provide(){ return { form:this } },
我们在form组件中直接将当前实例暴露出去
- 为了能实现input组件和formItem间的通信
import Vue from 'vue'; Vue.prototype.$bus = new Vue(); export default { props:{ label:String, prop:String }, mounted(){ this.$bus.$on('input',(value)=>{ console.log(value) }); } }
我们在formItem组件中,通过eventsBus订阅input事件
- 在input组件中监听输入事件进行数据的发射
handleInput(e){ // 更新数据 this.inputValue = e.target.value; this.$bus.$emit('input',{ id:this.$parent && this.$parent._uid,// 为了标识是哪个输入框 value:this.inputValue }); // 发射输入事件 }
- 在formItem中进行数据校验{{validateContent}}
到目前为止基本的校验功能已经实现啦
当点击按钮时校验当前表单是否验证成功 #
validate(){ // form组件中校验是通过
this.$refs.form.validate((valid)=>{
if(valid){
alert('校验通过')
}else{
alert('校验不通过')
}
});
}
// 在form组件中检查所有的formItem是否全部通过校验
validate(cb){
cb(this.$children.every(child=>child.validateStatus!='error'))
}