一、directives局部自定义指令
(注意:局部自定义指令 有两个条件【指令名称 和 指令对象】)
bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变
new Vue({
directives:{指令名:配置对象}
})
new Vue({
directives{指令名:回调函数}
})
directives:{
"nums":{
//绑定元素
bind(element,binding){
console.log(element);
console.log(binding);
element.innerText = binding.value*10;
console.log("-----------------");
},
//插入页面
inserted(element,binding){
console.log(element);
console.log(binding);
element.innerText = binding.value*100;
console.log("-----------------");
},
// 元素解析触发(值改变)
update(element,binding) {
console.log(element);
console.log(binding);
},
}
},
二、Vue全局自定义指令
(注意:Vue.directive(‘参数名称’,{}) 定义全局指令,它有两个参数)
Vue.directive第一个参数是指令的名字(不需要写上v-前缀),第二个参数可以是对象数据,也可以是一个指令函数
<div id="app">
<input type="text" v-focus>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{},
methods:{}
})
Vue.directive('focus',{
bind:function(){//每当指令绑定到元素上的时候,会立即执行这个 bind 函数,只执行一次
},
inserted:function(el){// inserted 表示元素 插入到DOM中的时候,会执行此函数,触发一次
el.focus(); //注意:在每一个函数中,第一个参数,永远是 el ,表示被绑定了指令的 那个元素 ,这个el参数,是一个原生JS的DOM对象
},
updated:function(){// 每当VNode 更新的时候,会执行 updated函数,可能会触发多次
}
})
</script>
三、自定义指令
规则:1.定义指令名称时不要使用v-和驼峰,需要使用-连接,需要加引号
2.使用时需要v-
3.对象式
“指令名”:{
绑定成功触发
bind(元素,绑定对象){},
插入页面触发
inserted(元素,绑定对象){},
元素解析触发(值改变)
update(元素,绑定对象){}
}
4.函数式
“指令名”(元素,绑定对象){}
1.局部自定指令
directives,需要定义在Vue实例中
2.全局自定义指令
directive,需要定义在Vue实例之前
四、vue自定义指令应用场景:
1、输入框自动聚焦
<input v-focus>
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
inserted: function (el) // 当被绑定的元素插入到 DOM 中时
el.focus()// 聚焦元素
}
})
2、设置一个v-lazy自定义指令完成图片懒加载
const LazyLoad = {
// install方法
install(Vue,options){
// 代替图片的loading图
let defaultSrc = options.default;
Vue.directive('lazy',{
bind(el,binding){
LazyLoad.init(el,binding.value,defaultSrc);
},
inserted(el){
// 兼容处理
if('IntersectionObserver' in window){
LazyLoad.observe(el);
}else{
LazyLoad.listenerScroll(el);
}
},
})
},
// 初始化
init(el,val,def){
// data-src 储存真实src
el.setAttribute('data-src',val);
// 设置src为loading图
el.setAttribute('src',def);
},
// 监听scroll事件
listenerScroll(el){
let handler = LazyLoad.throttle(LazyLoad.load,300);
LazyLoad.load(el);
window.addEventListener('scroll',() => {
handler(el);
});
},
// 加载真实图片
load(el){
let windowHeight = document.documentElement.clientHeight
let elTop = el.getBoundingClientRect().top;
let elBtm = el.getBoundingClientRect().bottom;
let realSrc = el.dataset.src;
if(elTop - windowHeight<0&&elBtm > 0){
if(realSrc){
el.src = realSrc;
el.removeAttribute('data-src');
}
}
},
// 节流
throttle(fn,delay){
let timer;
let prevTime;
return function(...args){
let currTime = Date.now();
let context = this;
if(!prevTime) prevTime = currTime;
clearTimeout(timer);
if(currTime - prevTime > delay){
prevTime = currTime;
fn.apply(context,args);
clearTimeout(timer);
return;
}
timer = setTimeout(function(){
prevTime = Date.now();
timer = null;
fn.apply(context,args);
},delay);
}
}
}
export default LazyLoad;