Verify 2 input boxes and one field of fixed telephone

In vue, verify the two input boxes before and after the fixed phone. Only one field is allowed to be verified on the parent page.

Solution: You can choose the component to pass by value

The value accepted by the input component by default is called——————props:{value}

The child component uses the $emit method to pass the value to the parent component———————input, the two values ​​divided into one value are passed to the value "telephone" in the parent component by default

Parent component

    <el-col :span="12">
                <el-form-item label="固定电话:" prop="telephone">
                  <telephone-input v-model="addForm.telephone"></telephone-input>
                </el-form-item>
    </el-col>

Sub-component

<template>
  <el-row>
    <el-col :span="4">
      <el-input v-model="areaCode"></el-input>
    </el-col>
    <el-col :span="2" class="line">
      <span>-</span>
    </el-col>
    <el-col :span="18">
      <el-input v-model="phoneCode"></el-input>
    </el-col>
  </el-row>
</template>

<script>
export default {
  name: 'telephone-input',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  computed: {
    areaCode: {
      get: function () {
        if (this.value) {
          let numberArr = this.value.split('-')
          if (numberArr.length) {
            return numberArr[0]
          } else {
            return undefined
          }
        }
      },
      set: function (newValue) {
        this.$emit('input', newValue + '-' + this.phoneCode)
      }
    },
    phoneCode: {
      get: function () {
        if (this.value) {
          let numberArr = this.value.split('-')
          if (numberArr.length) {
            return numberArr[1]
          } else {
            return undefined
          }
        }
      },
      set: function (newValue) {
        this.$emit('input', this.areaCode + '-' + newValue)
      }
    }
  },
  methods: {}
}
</script>

<style scoped>
  .line {
    text-align: center;
    line-height: 30px;
  }
</style>

 

Guess you like

Origin blog.csdn.net/qq_40055200/article/details/105563952