Vue的自定义指令
简单少量的input我们可以使用双向绑定后,watch到变化进行限制,如下:
<input id="ipt"type="text" v-model="iptVal"/> <script> var qwe=new Vue({ el:'#ipt', data(){ return{ iptVal:'' } }, watch:{ iptVal(val){ this.iptVal=val.replace(/[^0-9\.]/g, '') } } }) </script> |
但是,当面对大量的input输入框,我们更向往用简单的方式去解决,甚至简单到只写一个指令(比如v-limit)就可以。这样,我们就需要用到自定义指令的知识(可参考我的博客《Vue的土著指令和自定义指令》)。
这个value是随着输入不断更新的,因此,我们需要选用update这个钩子函数:
Vue.directive('limit', { update: function (el) { el.onkeypress = function (e) { var code = e.charCode; if (code != 0) { if (!String.fromCharCode(code).match(/[0-9\.]/)) { returnfalse; } } } el.addEventListener('textInput', function (e) { e.target.value = e.target.value.replace(/[^0-9\.]/g, '') }) el.onkeyup = function (e) { e.target.value = e.target.value.replace(/[^0-9\.]/g, '') } } }) |
此时,调用的方式特别简单,只需要增加“v-limit”这个指令即可。
<input id="ipt"type="text" v-model="iptVal" v-limit />
附完整代码,基于Vue的自定义指令的实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> </style> <script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js"></script> </head> <body> <input id="ipt" type="text" v-model="iptVal" v-focus/> </body> <script> Vue.directive('focus', { update: function (el) { el.onkeypress = function (e) { var code = e.charCode; if (code != 0) { if (!String.fromCharCode(code).match(/[0-9\.]/)) { return false; } } } el.addEventListener('textInput', function (e) { e.target.value = e.target.value.replace(/[^0-9\.]/g, '') }) el.onkeyup = function (e) { e.target.value = e.target.value.replace(/[^0-9\.]/g, '') } } }) var qwe = new Vue({ el: '#ipt', data() { return { iptVal: '' } }, watch:{ iptVal(val){ console.log(val) } } }) </script> |
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。