写一个Vue2和vue3的自定义指令(以复制指定作为示例)

13 篇文章 3 订阅

一、自定义指令是什么?

直接看官网的说明:带有v- 前缀的特殊 attribute(属性)

二、自定义指令有啥用?

作用:一个指令的任务是在其表达式的值变化时响应式地更新 DOM

<p v-if="seen">现在你看到我了</p>

v-if 指令会基于表达式 seen 的值的真假来移除/插入该 < p> 元素。

三、自定义指令怎么用?

1.自定义指令的参数

/*
* {string} id 自定义指令的名称
* {Function | Object} [definition] 自定义指令的回调函数
*/
Vue.directive( id, [definition] )

2.自定义指令的钩子函数

(1)五个钩子函数的说明

// 注册一个全局自定义指令 `my-directive`(Vue.directive注册自定义指令)
Vue.directive('my-directive', {
  bind(el, binding, vnode) {}, // 当指令绑定到元素上时调用
  inserted(el) {}, // 当绑定元素插入到 DOM 中时调用
  update(el, binding, vnode, oldVnode) {} // 在包含组件的 VNode 更新时调用
  componentUpdated(el, binding, vnode, oldVnode) {} // 在包含组件的 VNode 及其子 VNode 全部更新后调用
  unbind(el, binding, vnode) {} // 当指令与元素解绑时调用
});

(2)钩子函数的参数(主要参数:el和value)

el:指令所绑定的元素,可以用来直接操作 DOM。binding:一个对象,包含以下 property: name:指令名,不包括 v- 前缀。value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
expression:字符串形式的指令表达式。例如 v-my-directive=“1 + 1” 中,表达式为 “1 + 1”。
arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 “foo”。
modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
vnode:Vue 编译生成的虚拟节点。移步 VNode API 来了解更多详情。
oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

3.动态参数和修饰符

理论说完,直接看demo

(1)参数的使用

<div v-copy="value1的值"> 
// binding 参数会是一个这样的对象
{
  arg: 'copy',
  modifiers: {},
  value: /* `value1` 的值 */,
  oldValue: /* 上一次更新时 `value1` 的值 */
}
<div v-example:foo.bar="value2">
// 你将获得的binding 参数会是一个这样的对象
{
  arg: 'foo',
  modifiers: { bar: true },
  value: /* `value2` 的值 */,
  oldValue: /* 上一次更新时 `value2` 的值 */
}

(2)动态参数的使用

<div v-example:[arg]="value"></div>

(3)修饰符

同点击事件这种使用修饰符

// 提交事件使用

<form @submit.prevent="onSubmit">...</form>

// 自定义指令使用

<button v-copy.prevent="baz">...</button>
// v-copy 是定义的自定义名称
// prevent 是修饰符
// baz 是自定义的value

四、完整的vue2自定义指令使用

1. 在src下面创建directive文件夹(表示是自定义文件夹)

2. 新建文件copy.js(表示是个复制的自定义指令)

3. copy.js 的完整代码

import Vue from 'vue'
import { Message } from 'view-design' // 根据你使用的不同框架替换提示语句
// 注册一个全局自定义复制指令 `v-copy`
Vue.directive('copy', {
  // 参数1 ‘el’ 就是操作的dom,第二个参数就是binding,获取里面的属性value,也就是要复制的值
  bind (el, { value }) {
    el.$value = value
    el.handler = () => {
      el.style.position = 'relative'
      if (!el.$value) {
        // 值为空的时候,给出提示
        alert('无复制内容')
        return
      }
      // 动态创建 textarea 标签
      const textarea = document.createElement('textarea')
      // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
      textarea.readOnly = 'readonly'
      textarea.style.position = 'absolute'
      textarea.style.top = '0px'
      textarea.style.left = '-9999px'
      textarea.style.zIndex = '-9999'
      // 将要 copy 的值赋给 textarea 标签的 value 属性
      textarea.value = el.$value
      // 将 textarea 插入到 el 中
      el.appendChild(textarea)
      // 兼容IOS 没有 select() 方法
      if (textarea.createTextRange) {
        textarea.select() // 选中值并复制
      } else {
        textarea.setSelectionRange(0, el.$value.length)
        textarea.focus()
      }
      const result = document.execCommand('Copy')
      if (result) Message.success('复制成功')
      el.removeChild(textarea)
    }
    el.addEventListener('click', el.handler) // 绑定点击事件
  },
  // 当传进来的值更新的时候触发
  componentUpdated (el, { value }) {
    el.$value = value
  },
  // 指令与元素解绑的时候,移除事件绑定
  unbind (el) {
    el.removeEventListener('click', el.handler)
  }
})

4 .main.js

因为在copy.js中

import './directive/copy'

五、局部指令(了解)

全局指令:通过 Vue.directive() 函数注册一个全局的指令。
局部指令:通过组件的 directives 属性,对该组件添加一个局部的指令
注意点:==directives 和 methods 确实是同级的配置项,别放在methods里面了。==其他使用同全局指令。

directives: {
  copy: {
    // 指令的定义
    inserted: function (el) {
      // 复制逻辑,不在重复了
    }
  }
}

六、完整的vue3自定义指令使用(全局和局部)

1. 指令钩子

const myDirective = {
  // 在绑定元素的 attribute 前
  // 或事件监听器应用前调用
  created(el, binding, vnode) {
    // 下面会介绍各个参数的细节
  },
  // 在元素被插入到 DOM 前调用
  beforeMount(el, binding, vnode) {},
  // 在绑定元素的父组件
  // 及他自己的所有子节点都挂载完成后调用
  mounted(el, binding, vnode) {},
  // 绑定元素的父组件更新前调用
  beforeUpdate(el, binding, vnode, prevVnode) {},
  // 在绑定元素的父组件
  // 及他自己的所有子节点都更新后调用
  updated(el, binding, vnode, prevVnode) {},
  // 绑定元素的父组件卸载前调用
  beforeUnmount(el, binding, vnode) {},
  // 绑定元素的父组件卸载后调用
  unmounted(el, binding, vnode) {}
}

2. 钩子参数

el:指令绑定到的元素。这可以用于直接操作 DOM。

binding:一个对象,包含以下属性。

value:传递给指令的值。例如在 v-my-directive="1 + 1" 中,值是 2。
oldValue:之前的值,仅在 beforeUpdate 和 updated 中可用。无论值是否更改,它都可用。
arg:传递给指令的参数 (如果有的话)。例如在 v-my-directive:foo 中,参数是 "foo"modifiers:一个包含修饰符的对象 (如果有的话)。例如在 v-my-directive.foo.bar 中,修饰符对象是 { foo: true, bar: true }。
instance:使用该指令的组件实例。
dir:指令的定义对象。
vnode:代表绑定元素的底层 VNode。

prevVnode:代表之前的渲染中指令所绑定元素的 VNode。仅在 beforeUpdate 和 updated 钩子中可用。


3. 全局自定义组件的使用

(1) 在src下面创建directive文件夹(表示是自定义文件夹)

(2)新建文件copy.js(表示是个复制的自定义指令)

(3)copy.ts 的完整代码

import { DirectiveBinding } from 'vue';
import { message } from 'ant-design-vue'
// 注册一个全局自定义复制指令 `v-copy`
const copy = {
  // 在绑定元素的父组件及他自己的所有子节点都挂载完成后调用
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    el.addEventListener('click', () => {
      const textToCopy = binding.value;
      if (textToCopy) {
        // 如果支持Clipboard API
        if (navigator.clipboard && navigator.clipboard.writeText) {
          navigator.clipboard.writeText(textToCopy).then(() => {
            message.success('复制成功!')
          }).catch(err => {
            message.error(err + '复制失败!')
          });
        } else {
          // 不支持创建一个临时的 textarea 元素来实现复制功能
          const textarea = document.createElement('textarea');
          textarea.value = textToCopy;
          textarea.style.position = 'fixed';
          document.body.appendChild(textarea);
          textarea.focus();
          textarea.select();
          try {
            document.execCommand('copy');
            message.success('复制成功!')
          } catch (err) {
            message.error(err + '复制失败!')
          }
          document.body.removeChild(textarea);
        }
      }
    });
  },
  // 绑定元素的父组件卸载后调用
  unmounted(el: HTMLElement) {
    el.removeEventListener('click', () => {});
  }
}
export default copy

(4)main.ts

import { createApp } from 'vue'
import App from './App.vue'
import copy from './directive/copy'
const app = createApp(App)
app.directive('copy', copy);
app.mount('#app')

4. setup函数的局部组件使用

<template>
  <div>
    <input v-model="text" placeholder="Enter text to copy" />
    <button v-copy="text">Copy Text</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const text = ref('');
    // 定义局部指令
    const copyDirective = {
      mounted(el, binding) {
        el.addEventListener('click', () => {
        });
      },
      unmounted(el) {
        el.removeEventListener('click', () => {});
      }
    };
    return {
      text,
      directives: {
        copy: copyDirective
      }
    };
  }
};
</script>

5. setup script的局部组件使用

<template>
  <divvue
<template>
  <div>
    <input v-model="text" placeholder="Enter text to copy" />
    <button v-copy="text">Copy Text</button>
  </div>
</template>

<script setup>
import { ref, directive } from 'vue';

// 定义局部指令
const copyDirective = {
  mounted(el, binding) {
    el.addEventListener('click', () => {
    });
  },
  unmounted(el) {
    el.removeEventListener('click', () => {});
  }
};

// 注册局部指令
const directives = {
  copy: copyDirective
};

// 定义响应式数据
const text = ref('');
</script>

6. setup 函数和setup script的局部指令使用 代码图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值