前端vue.js道

3 自定义(重要)

2016-11-15  本文已影响10人  0efb885b580c

循环

v-for="value in data"
会有重复数据?
track-by='索引'   提高循环性能
track-by='$index/uid'

过滤器

vue提供过滤器:
        capitalize  uppercase   currency....
//debounce配合事件,延迟执行
        <input type="text" @keyup="show | debounce 2000">//延迟两秒执行debounce   
数据配合使用过滤器:
//limitBy 参数(取几个)
    <li v-for="value in arr | limitBy 2"> {{value}} </li>   //limitBy   限制2个
//limitBy(取几个  从哪开始)
        <li v-for="val in arr | limitBy 2 arr.length-2"> {{val}}</li>
//filterBy  过滤数据     
        <li v-for="val in arr | filterBy 'w'">{{val}}</li>//显示所有带w的
//orderBy   排序
        //todo  未确定
    orderBy 谁 1/-1
            1  -> 正序
            2  -> 倒序

自定义过滤器: filter

自定义过滤器: filter           model ->过滤 -> view
Vue.filter('toDou',function(input){//参数是a的值
    return input<10?'0'+input:''+input;
});
{{a | toDou}}//data:{a:9}
//传参
Vue.filter('toDou',function(input,one,two){//参数是a的值   one,two是接受的参数
    return input<10?'0'+input:''+input;
});
{{a | toDou 1 2}}//data:{a:9}

自定义指令 directive * 注意: 必须以 v-开头

Vue.directive(指令名称,function(参数){
    this.el -> 原生DOM元素
});
Vue.directive('red',function(){
     this.el.style.background='red';
});
<span v-red>asdfasd </span>
自定义元素指令:(用处不大)
Vue.elementDirective('zns-red',{
      bind:function(){
        this.el.style.background='red';
      }
});
<zns-red></zns-red>

自定义键盘事件

普通的事件@keydown.up   @keydown.enter   @keydown.a/b/c.... 
Vue.directive('on').keyCodes.ctrl=17;//添加自定义事件
<input type="text" @keydown.ctrl="show">

监听数据变化

vm.$watch(name,fnCb);  //浅度
vm.$watch(name,fnCb,{deep:true});  //深度监视 
vm.$el/$mount/$options/....
vm.$watch('a',function(){ //data:{a:111, b:2}
         alert('发生变化了');
         this.b=this.a+100;
});
document.onclick=function(){  vm.a=1;};

双向过滤

Vue.filter('filterHtml',{
   read:function(input){ //model-view
         alert(1);
         return input.replace(/<[^<]+>/g,'');
   },
   write:function(val){ //view -> model
         console.log(val);
        return val;
    }
});
<input type="text" v-model="msg | filterHtml">
上一篇 下一篇

猜你喜欢

热点阅读