How to remove the spaces before and after vue element-ui to space

First, the problem
vue in when the user submits the form, the data need to be removed around some space and then send back end again.

Second, the solution
can first use the v-model.trim the v-model modifier to solve it, but when the user enters \ u200B, this method does not work, and then we can go to the v-model.trim this modification Fu source

function genDefaultModel (
  el: ASTElement,
  value: string,
  modifiers: ?ASTModifiers
): ?boolean {
  const type = el.attrsMap.type
  const { lazy, number, trim } = modifiers || {}
  const needCompositionGuard = !lazy && type !== 'range'
  const event = lazy
    ? 'change'
    : type === 'range'
      ? RANGE_TOKEN
      : 'input'
 
  let valueExpression = '$event.target.value'
   // 去掉空格
  if (trim) {
    valueExpression = `$event.target.value.trim()`
  }
  if (number) {
    valueExpression = `_n(${valueExpression})`
  }
 
  let code = genAssignmentCode(value, valueExpression)
  if (needCompositionGuard) {
    code = `if($event.target.composing)return;${code}`
  }
 
  addProp(el, 'value', `(${value})`)
  addHandler(el, event, code, null, true)
  if (trim || number || type === 'number') {
    addHandler(el, 'blur', '$forceUpdate()')
  }
}

The above source approach we can understand this as the following way:

<input :value="name" @input="if($event.target.composing)return;name=$event.target.value.trim()" type="text"/>

So we can put the above methods to strengthen or improve it:

<template>
  <div @input="removeSpaces">
    <el-input v-model.trim="value"></el-input>
  </div>
</template>
<script>
    export default {
        data() {
            return {
                value : ''
            }
        },
        methods: {
            removeSpaces(event) {
                if(event.target.composing){
                    return
            }
            this.value = event.target.value.trim()
            this.value = this.value.replace("\\u200B","")
          }
        }
    }
</script>

Similarly, we can use this method to customize some of the other features of the input box assembly

Published 18 original articles · won praise 16 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_44569012/article/details/102536483