Vue2自定义指令深度解析:5个高效开发实战技巧
1. 基础指令实现
创建元素聚焦指令:
// 注册全局指令
Vue.directive('focus', {
inserted(el) {
el.focus();
}
});
// 使用
<input v-focus placeholder="自动聚焦">
Vue.directive(‘focus’, {
inserted(el) {
el.focus();
}
});
new Vue({ el: ‘#app’ });
2. 指令参数传递
实现动态样式绑定:
Vue.directive('pin', {
bind(el, binding) {
el.style.position = 'fixed';
el.style[binding.arg || 'top'] = binding.value + 'px';
},
update(el, binding) {
el.style[binding.arg || 'top'] = binding.value + 'px';
}
});
// 使用
<div v-pin:left="200">固定在左侧200px处</div>
3. 高级工具提示
自定义指令实现Tooltip:
Vue.directive('tooltip', {
bind(el, binding) {
const tooltip = document.createElement('div');
tooltip.className = 'tooltip';
tooltip.textContent = binding.value;
document.body.appendChild(tooltip);
el.addEventListener('mouseenter', () => {
const rect = el.getBoundingClientRect();
tooltip.style.display = 'block';
tooltip.style.left = `${rect.left}px`;
tooltip.style.top = `${rect.bottom + 5}px`;
});
el.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
}
});
// 使用
<button v-tooltip="'点击提交表单'">提交</button>
4. 权限控制指令
实现按钮权限控制:
Vue.directive('permission', {
inserted(el, binding) {
const permissions = ['admin', 'editor'];
if (!permissions.includes(binding.value)) {
el.style.display = 'none';
}
}
});
// 使用
<button v-permission="'admin'">管理员按钮</button>
钩子函数 | 调用时机 | 常用操作 |
---|---|---|
bind | 指令第一次绑定到元素 | 初始设置 |
inserted | 被绑定元素插入父节点 | DOM操作 |
update | 组件更新时 | 更新逻辑 |
5. 电商实战:图片懒加载
高性能图片懒加载实现:
Vue.directive('lazy', {
inserted(el, binding) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
el.src = binding.value;
observer.unobserve(el);
}
});
});
observer.observe(el);
// 设置占位图
el.src = 'placeholder.jpg';
}
});
// 使用
<img v-lazy="'product-image.jpg'" alt="商品图片">
Vue2自定义指令为DOM操作提供了优雅的封装方式,特别适合工具提示、权限控制、性能优化等需要直接操作DOM的场景,能大幅提升代码复用性和可维护性。