Vue el-input 限制输入内容

🤔日常项目中经常遇到既要el-input的样式,又要el-input-number限制,所以需要绑定@input事件进行约束输入限制。

以下使用自定义指令进行约束el-input输入的值,便于后期统一管理和拓展。

预览
代码
html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./assets/global.css">

    <!-- 引入样式 -->
    <link rel="stylesheet" href="./assets/element-ui/lib/theme-chalk/index.css">
</head>

<body>
    <div id="app">
        输入框
        <el-input v-model="num" v-only-number></el-input>
        预览值
        <div>{{num}}</div>
    </div>
</body>
<!-- import Vue before Element -->
<script src="./assets/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="./assets/element-ui/lib/index.js"></script>

<script>

    new Vue({
        el: '#app',
        data: function () {
            return {
                num: ''
            }
        },
        directives: {
            onlyNumber: {
                inserted: function (el, binding, vnode) {
                    vnode.elm.addEventListener('input', function (e) {
                        // 取出原始值
                        let value = e.target.value.replace(/[^0-9]/g, '')
                        // 重置原始值
                        e.target.value = value
                        // 向上更新
                        vnode.componentInstance.$emit('input', value)
                    })
                }
            }
        }
    })

</script>

</html>

在线预览
https://linyisonger.github.io/H5.Examples/

源码仓库
https://github.com/linyisonger/H5.Examples.git

相关推荐
天宇&嘘月2 小时前
web第三次作业
前端·javascript·css
小王不会写code2 小时前
axios
前端·javascript·axios
发呆的薇薇°3 小时前
vue3 配置@根路径
前端·vue.js
luoluoal3 小时前
基于Spring Boot+Vue的宠物服务管理系统(源码+文档)
vue.js·spring boot·宠物
luckyext4 小时前
HBuilderX中,VUE生成随机数字,vue调用随机数函数
前端·javascript·vue.js·微信小程序·小程序
小小码农(找工作版)4 小时前
JavaScript 前端面试 4(作用域链、this)
前端·javascript·面试
前端没钱4 小时前
前端需要学习 Docker 吗?
前端·学习·docker
前端郭德纲4 小时前
前端自动化部署的极简方案
运维·前端·自动化
海绵宝宝_4 小时前
【HarmonyOS NEXT】获取正式应用签名证书的签名信息
android·前端·华为·harmonyos·鸿蒙·鸿蒙应用开发
码农土豆5 小时前
chrome V3插件开发,调用 chrome.action.setIcon,提示路径找不到
前端·chrome