# share-directive
**Repository Path**: good-chil/share-directive
## Basic Information
- **Project Name**: share-directive
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2023-08-14
- **Last Updated**: 2023-08-14
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# vue 自定义指令推荐
在 Vue,除了核心功能默认内置的指令 ( v-model 和 v-show ),Vue 也允许注册自定义指令。它的作用价值在于当开发人员在某些场景下需要对普通 DOM 元素进行操作。
Vue 自定义指令有全局注册和局部注册两种方式。先来看看注册全局指令的方式,通过 `Vue.directive( id, [definition] )` 方式注册全局指令。然后在入口文件中进行 `Vue.use()` 调用。
批量注册指令,新建 `directives/directive.js` 文件
```js
import copy from "./copy";
import longpress from "./longpress";
// 自定义指令
const directives = {
copy,
longpress,
};
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key]);
});
},
};
```
在 `main.js` 引入并调用
```js
import Vue from "vue";
import Directives from "./directives/directive.js";
Vue.use(Directives);
```
指令定义函数提供了几个钩子函数(可选):
- bind: 只调用一次,指令第一次绑定到元素时调用,可以定义一个在绑定时执行一次的初始化动作,此时获取父节点为 null。
- inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中),此时可以获取到父节点。
- update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值。
- componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
- unbind: 只调用一次, 指令与元素解绑时调用。
下面分享几个实用的 Vue 自定义指令
- 表单验证指令 `v-validate`
- 长按指令 `v-longpress`
- 函数防抖指令 `v-debounce`
- 函数节流指令 `v-throttle`
- 点击元素外部指令 `v-click-out`
- 弹窗限制外部滚动指令 `v-scroll-pop`
- 加载指令 `v-loading`
- 埋点指令`v-sensor`
## v-copy
需求:实现一键复制文本内容,用于鼠标右键粘贴。
思路:
1. 动态创建 `textarea` 标签,并设置 `readOnly` 属性及移出可视区域
2. 将要复制的值赋给 `textarea` 标签的 `value` 属性,并插入到 `body`
3. 选中值 `textarea` 并复制
4. 将 `body` 中插入的 `textarea` 移除
5. 在第一次调用时绑定事件,在解绑时移除事件
```js
const copy = {
bind(el, { value }) {
el.$value = value;
el.handler = () => {
if (!el.$value) {
// 值为空的时候,给出提示。可根据项目UI仔细设计
console.log("无复制内容");
return;
}
// 动态创建 textarea 标签
const textarea = document.createElement("textarea");
// 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
textarea.readOnly = "readonly";
textarea.style.position = "absolute";
textarea.style.left = "-9999px";
// 将要 copy 的值赋给 textarea 标签的 value 属性
textarea.value = el.$value;
// 将 textarea 插入到 body 中
document.body.appendChild(textarea);
// 选中值并复制
textarea.select();
const result =
(document.execCommand && document.execCommand("Copy")) || false;
if (result) {
console.log("复制成功"); // 可根据项目UI仔细设计
} else {
console.log("复制失败,请手动复制");
}
document.body.removeChild(textarea);
};
// 绑定点击事件
el.addEventListener("click", el.handler);
},
// 当传进来的值更新的时候触发
componentUpdated(el, { value }) {
el.$value = value;
},
// 指令与元素解绑的时候,移除事件绑定
unbind(el) {
el.removeEventListener("click", el.handler);
},
};
export default copy;
```
使用:给 Dom 加上 `v-copy` 及复制的文本即可
```html
```
## v-longpress
需求:实现长按,用户需要按下并按住按钮几秒钟,触发相应的事件
思路:
1. 创建一个计时器, n 秒后执行函数
2. 当用户按下按钮时触发 `mousedown` 事件,启动计时器;用户松开按钮时调用` mouseout` 事件。
3. 如果 `mouseup` 事件 n 秒内被触发,就清除计时器,当作一个普通的点击事件
4. 如果计时器没有在 n 秒内清除,则判定为一次长按,可以执行关联的函数。
5. 在移动端要考虑 `touchstart`,`touchend` 事件
```js
const longpress = {
bind: function (el, { value: { fn, time } }, vNode) {
//没绑定函数直接返回
if (typeof fn !== "function") return;
// 定义定时器变量
el.pressTimer = null;
// 创建计时器( 2秒后执行函数 )
el._start = (e) => {
//e.type表示触发的事件类型如mousedown,touchstart等
//pc端: e.button表示是哪个键按下0为鼠标左键,1为中键,2为右键
//移动端: e.touches表示同时按下的键为个数
if (
(e.type === "mousedown" && e.button && e.button !== 0) ||
(e.type === "touchstart" && e.touches && e.touches.length > 1)
)
return;
//定时长按两秒后执行事件
if (el.pressTimer === null) {
el.pressTimer = setTimeout(() => {
fn();
}, time);
//取消浏览器默认事件,如右键弹窗
el.addEventListener("contextmenu", function (e) {
e.preventDefault();
});
}
};
// 如果两秒内松手,则取消计时器
el._cancel = (e) => {
if (el.pressTimer !== null) {
clearTimeout(el.pressTimer);
el.pressTimer = null;
}
};
// 添加事件监听器
el.addEventListener("mousedown", el._start);
el.addEventListener("touchstart", el._start);
// 取消计时器
el.addEventListener("click", el._cancel);
el.addEventListener("mouseout", el._cancel);
el.addEventListener("touchend", el._cancel);
el.addEventListener("touchcancel", el._cancel);
},
// 指令与元素解绑的时候,移除事件绑定
unbind(el) {
// 移除事件监听器
el.removeEventListener("mousedown", el._start);
el.removeEventListener("touchstart", el._start);
// 移除取消计时器
el.removeEventListener("click", el._cancel);
el.removeEventListener("mouseout", el._cancel);
el.removeEventListener("touchend", el._cancel);
el.removeEventListener("touchcancel", el._cancel);
},
};
export default longpress;
```
使用:给 Dom 加上 `v-longpress` 及回调函数即可
```html
```
## v-debounce
背景:在开发中,有时遇到要给 input 或者滚动条添加监听事件,需要做防抖处理。
需求:防止 input 或 scroll 事件在短时间内被多次触发,使用防抖函数限制一定时间后触发。
思路:
1. 定义一个延迟执行的方法,如果在延迟时间内再调用该方法,则重新计算执行时间。
2. 将事件绑定在传入的方法上。
```js
const debounce = {
inserted: function (el, { value: { fn, event, time } }) {
//没绑定函数直接返回
if (typeof fn !== "function") return;
//监听点击事件,限定事件内如果再次点击则清空定时器并重新定时
el.addEventListener(event, () => {
if (el._timer) {
clearTimeout(el._timer);
}
el._timer = setTimeout(() => {
fn();
}, time);
});
},
};
export default debounce;
```
使用:给 Dom 加上 `v-debounce` 及回调函数即可
```html
文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文
字文字文字文字
文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文
字文字文字文字
文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文
字文字文字文字
文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文
字文字文字文字
文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文
字文字文字文字
我是内容