vue中表格使用自定义input框实现表单校验

136 阅读1分钟

具体实现

子组件定义

<template>
  <div class="container">
    <LabelName />
    <div class="input_sty">
        <input :value="row.address" @input="input"></input>
        <div v-if="isShowMsg">地址不可为空 </div>
    </div>
    <!-- <span v-if="true">+</span>
    <span v-else>-</span> -->
    <!-- <img
      class="img"
      v-if="true"
      :src="require('@/assets/img/1.png')"
    />
    <img
      class="img"
      v-else
      :src="require('@/assets/img/2.png')"
    /> -->
  </div>
</template>

<script>
import LabelName from './labelName.vue'

export default {
  components: {
    LabelName
  },
  props:{
    row:Object
  },
  mounted(){
   // console.log(this,'this');
    this.isShowMsg = this.$attrs.reg.test(this.row.address)
    
  },
  data() {
    return {
        isShowMsg:false
    }
  },
  methods: {
    input(event){
       // console.log(event,'event');
        // eslint-disable-next-line vue/no-mutating-props
        this.row.address = event.target?.value
        this.isShowMsg = this.$attrs.reg.test(this.row.address)
        console.log( this.isShowMsg);
        
        this.$emit('changeRow',this.row)
    }
  },
  watch:{
    'row.address'(value){
       // console.log(value,'row');
    //    console.log(this.$attrs.reg instanceof RegExp,'this.$attrs.reg');
        
    }
  }
}
</script>

<style scoped>
.img {
  width: 20px;
  height: 20px;
}
.container {
  display: flex;
  width: 40%;
  /* align-items: center; */
 /* // height: 60px; */
  .input_sty{
    display: flex;
    flex-direction: column;
  }
}
span {
  margin-left: 5px;
  margin-top: 4px;
}
input{
    border: 1px solid navy;
    height: 30px;
}
</style>

父组件传参

  <template #default="{ row }">
      <InfoSource
        @changeRow="changeRow"
        :row="row"
        :reg="reg"
      />
    </template>
    // 关键在于 使用row传给子组件,子组件绑定row。属性改变row中的属性,不会引起props修改报警,也能修改数组

效果展示

image.png

image.png