vue中如何去掉空格的方法實現(xiàn)
一、問題
vue中當(dāng)用戶提交表單時,有的數(shù)據(jù)需要去掉前后空格然后再向后端發(fā)送。
二、解決方法
首先可以使用v-model.trim這個v-model修飾符去解決它,但是當(dāng)用戶輸入\u200B時,這個方法就不奏效了,這時我們可以去一下v-model.trim這個修飾符的源碼
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()') } }
上面的源碼處理方式我們也可以理解為下面這種方式:
所以我們可以把上面的方法強化或者改進一下:
<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>
同理,使用這種方法我們可以定制一些其他功能的輸入框組件
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3.0之引入Element-plus ui樣式的兩種方法
本文主要介紹了Vue3.0之引入Element-plus ui樣式的兩種方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02vue3實現(xiàn)無縫滾動列表效果(大屏數(shù)據(jù)輪播場景)
vue3-scroll-seamless 是一個用于 Vue 3 的插件,用于實現(xiàn)無縫滾動的組件,它可以讓內(nèi)容在水平或垂直方向上無縫滾動,適用于展示輪播圖、新聞滾動、圖片展示等場景,本文就給大家介紹了vue3實現(xiàn)無縫滾動列表效果,需要的朋友可以參考下2024-07-07