需求
當(dāng)用戶輸入的時(shí)候,我們需要自動(dòng)去掉輸入框兩邊的空格, 注意,中間是能輸入空格的
我們一般使用的是?v-model.trim,
原生的input框是可以的,但封裝之后的會(huì)把所有空格都去掉,例如el-input.
此時(shí)我們利用全局自定義指令實(shí)現(xiàn)對(duì)el-input的只去除首尾空格的需求。
1、在directive文件夾下創(chuàng)建一個(gè)trim文件夾?
??
2、index.js文件?
/**
* 去除兩邊空格
* 使用 <el-input v-model="xxx" v-trim></el-input>
*/
function getInput(el) {
let inputEle
if (el.tagName !== 'INPUT') {
inputEle = el.querySelector('input')
} else {
inputEle = el
}
return inputEle
}
function dispatchEvent(el, type) {
let evt = document.createEvent('HTMLEvents')
evt.initEvent(type, true, true)
el.dispatchEvent(evt)
}
const Trim = {
inserted: el => {
let inputEle = getInput(el)
const handler = function (event) {
const newVal = event.target.value.trim()
if (event.target.value != newVal) {
event.target.value = newVal
dispatchEvent(inputEle, 'input')
}
}
el.inputEle = inputEle
el._blurHandler = handler
inputEle.addEventListener('blur', handler)
},
unbind(el) {
const { inputEle } = el
inputEle.removeEventListener('blur', el._blurHandler)
}
}
export default Trim
3、引入
4、在main.js中全局引入定義好的directive?
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-659142.html
import directive from './directive' // directive
Vue.use(directive)
5、使用
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-659142.html
到了這里,關(guān)于vue利用自定義指令全局去除el-input框前后空格的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!