闽公网安备 35020302035485号
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus() // 页面加载完成之后自动让输入框获取到焦点的小功能
}
})
局部注册directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus() // 页面加载完成之后自动让输入框获取到焦点的小功能
}
}
}
然后你可以在模板中任何元素上使用新的 v-focus property,如下:<input v-focus />
unbind:只调用一次,指令与元素解绑时调用
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
<script>
Vue.directive('demo', function (el, binding) {
console.log(binding.value.color) // "white"
console.log(binding.value.text) // "hello!"
})
</script>
三、自定义指令的应用场景3.一键 Copy的功能
表单防止重复提交
表单防止重复提交这种情况设置一个v-throttle自定义指令来实现// 堆代码 duidaima.com
// 1.设置v-throttle自定义指令
Vue.directive('throttle', {
bind: (el, binding) => {
let throttleTime = binding.value; // 节流时间
if (!throttleTime) { // 用户若不设置节流时间,则默认2s
throttleTime = 2000;
}
let cbFun;
el.addEventListener('click', event => {
if (!cbFun) { // 第一次执行
cbFun = setTimeout(() => {
cbFun = null;
}, throttleTime);
} else {
event && event.stopImmediatePropagation();
}
}, true);
},
});
// 2.为button标签设置v-throttle自定义指令
<button @click="sayHello" v-throttle>提交</button>
图片懒加载// 创建一个 Vue 自定义指令
Vue.directive('lazy', {
// 当被绑定的元素插入到 DOM 中时
inserted: function (el, binding) {
// 使用 IntersectionObserver 监听元素是否进入可视区域
let observer = new IntersectionObserver(function (entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 如果元素进入可视区域,则加载图片
el.src = binding.value;
observer.unobserve(el);
}
});
});
// 开始监听目标元素
observer.observe(el);
}
});
一键 Copy的功能// 创建一个 Vue 自定义指令
Vue.directive('copy', {
bind(el, binding) {
el.addEventListener('click', () => {
// 创建一个临时的文本域
const textField = document.createElement('textarea');
textField.innerText = binding.value;
document.body.appendChild(textField);
// 选中文本域中的文本
textField.select();
// 尝试复制文本到剪贴板
try {
document.execCommand('copy');
alert('文本已成功复制到剪贴板');
} catch (err) {
alert('无法复制文本到剪贴板,请手动复制');
} finally {
// 移除临时文本域
textField.remove();
}
});
}
});