<!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>限制input输入的位数</title>
</head>
<body>
<div id="app">
<input type="text" v-split.5="msg"/>
</div>
</body>
<script src="./node_modules/vue/dist/vue.js"></script>
<script>
//设置input 的输入位数
Vue.directive(‘split‘,{
update(el,bindings,vnode) {
console.log(bindings);
let [,len] = bindings.rawName.split(‘.‘);
console.log(len)
let ctx = vnode.context; //msg
el.addEventListener(‘input‘,(e)=>{
let val = e.target.value.slice(0,len);
ctx[bindings.expression]=val;
el.value = val;
})
//默认值
el.value=ctx[bindings.expression];
},
bind(el,bindings,vnode) {
let ctx = vnode.context; //msg
let [,len] = bindings.rawName.split(‘.‘);
el.addEventListener(‘input‘,(e)=>{
let val = e.target.value.slice(0,len);
ctx[bindings.expression]=val;
el.value = val;
})
//默认值
el.value=ctx[bindings.expression];
}
})
let vm = new Vue({
el:"#app",
data() {
return {
msg:‘a‘
}
}
})
</script>
</html>
el,bindings,vnode
el表示 html 元素
bindings 表示绑定的元素上的属性
vnode 表示绑定元素的虚拟node