z-form.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <template>
  2. <form @submit="formSubmit" @reset="formReset">
  3. <slot />
  4. </form>
  5. </template>
  6. <script>
  7. import bus from '../../utils/bus.js'
  8. export default {
  9. name: "z-form",
  10. props: {
  11. reportSubmit: {
  12. type: Boolean,
  13. default: false
  14. },
  15. model: Object,
  16. rules: Object
  17. },
  18. data() {
  19. return {
  20. once:false,
  21. };
  22. },
  23. watch: {
  24. model: {
  25. deep: true,
  26. handler: function(newval, oldval) {
  27. // console.log(newval)
  28. this.valiateValue();
  29. }
  30. },
  31. rules: {
  32. deep: true,
  33. handler: function(newval, oldval) {
  34. // console.log(newval)
  35. this.valiateValue();
  36. }
  37. },
  38. },
  39. mounted() {
  40. this.valiateValue();
  41. },
  42. methods: {
  43. valiateValue() {
  44. console.log(this.model)
  45. bus.$emit('valiate', {model:this.model,rules:this.rules})
  46. },
  47. formSubmit(e) {
  48. this.$emit('submit',e)
  49. },
  50. formReset(e) {
  51. this.$emit('reset',e)
  52. },
  53. // 规则校验
  54. validate(callback) {
  55. let vb = true
  56. //获取表单下所有的子项目,如果显示了提示代表数据输入错误
  57. let item = this.getItem(this.$children)
  58. console.log(item)
  59. for(let i=0 ; i < item.length; ++i){
  60. item[i].appear=true;
  61. }
  62. for(let i = 0; i < item.length; ++i) {
  63. // 对表单下的子组件 form-item 做数据校验
  64. let bol = item[i].isError ? false : true
  65. if(vb && !bol) {
  66. vb = false
  67. }
  68. if(this.msgType != 'in' && !bol) {
  69. break
  70. }
  71. }
  72. console.log(item)
  73. callback && callback(vb)
  74. },
  75. // 递归遍历子元素 筛选 form-item
  76. getItem(children,item) {
  77. item = item || []
  78. children.forEach(it => {
  79. if(it.$options.name && it.$options.name === 'ZFormItem' ||
  80. it.$options._componentTag && it.$options._componentTag === 'z-form-item'){
  81. item.push(it)
  82. } else if(it.$children.length){
  83. item = this.getItem(it.$children,item)
  84. }
  85. })
  86. return item
  87. }
  88. // validate(){
  89. // bus.$on('validateResult',(data)=>{
  90. // console.log(1)
  91. // })
  92. // console.log(this.$slots)
  93. // }
  94. }
  95. }
  96. </script>
  97. <style lang="scss">
  98. </style>