image.pngv-model的强大之处。同步输入指令同步改变。模拟复选,多选等。样式比较简单没写主要是逻辑。
v-model的多选,单选,复选。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="vue.min.js"></script>
<style>
*{
margin:0;
padding:0;
}
#box div{
padding:20px 20px;
border-bottom:1px solid red;
}
</style>
</head>
<body>
<div id="box">
<div>
<h3>input框的实现</h3>
<input type="text" v-len="name" >
<p>{{name}}</p>
</div>
<div>
<h3>checkbox的实现</h3>
<input type="checkbox" value="我是checkbox1" v-len="che_flag"> 我是checkbox1<br/>
<input type="checkbox" value="我是checkbox2" v-len="che_flag1"> 我是checkbox2
<p>{{che_flag}} {{che_flag1}}</p>
<p>{{arr}}</p>
</div>
<div>
<h3>单选框的实现</h3>
<input type="radio" value="one" v-len="str" name="a"> one<br/><!--必须要有name属性-->
<input type="radio" value="two" v-len="str" name="a"> two
<p>{{str}}</p>
</div>
<div>
<h3>多选框实现</h3>
<select v-veb="str1">
<option>veb</option>
<option>len</option>
<option>veblen</option>
</select>
<p>{{str1}}</p>
</div>
</div>
</body>
<script>
Vue.directive("len",{
inserted:function(el,binding,vnode){
// console.log(vnode.context.arr)
if(el.type=="text"){
el.value=binding.value;
//当input框的值发生改变的时候
el.addEventListener("input",function(){
vnode.context[binding.expression]=el.value;
})
}
if(el.type=="checkbox"){
el.checked=binding.value;
if(el.checked){
vnode.context.arr.push(el.value)
}
el.addEventListener("click",function(){
vnode.context[binding.expression]=el.checked;
if(vnode.context[binding.expression]){
vnode.context.arr.push(el.value)
}else{
var len=vnode.context.arr.length
for(var i=0;i<len;i++){
if(vnode.context.arr[i]==el.value){
vnode.context.arr.splice(i,1)
}
}
}
})
}
if (el.type==="radio") {
el.checked=false;
el.addEventListener("click",function(){
this.checked=true;
vnode.context[binding.expression]=this.value;
})
}
},
//当data发生改变的时候
update:function(el,binding,vnode){
if(vnode.data.attrs.type=="text"){
el.value=binding.value;
}
if(vnode.data.attrs.type=="checkbox"){
el.checked=binding.value;
}
}
})
Vue.directive("veb",{
inserted:function(el,binding,vnode){
binding.value=el.selected
el.addEventListener("change",function(){
console.log(el.selected)
})
},
update:function(el,binding,vnode){
}
})
var box=new Vue({
el:"#box",
data:{
name:"veb",
che_flag:true,
che_flag1:true,
arr:[],
rad_flag1:false,
// rad_flag2:false,
str:"",
sel_flag:false,
str1:""
}
})
</script>
</html>
网友评论