目录

一、定义

二、声明周期

三、钩子参数

四、全局注册

五、封装鉴权指令


一、定义

一个自定义指令由一个包含类似组件生命周期钩子的对象来定义。钩子函数会接收到指令所绑定元素作为其参数
在setup中,任何以 v 开头的驼峰式命名的变量都可以被用作一个自定义指令。在上面的例子中,vFocus 即可以在模板中以 v-focus 的形式使用。

:页面加载时输入框自动聚焦:

<script setup lang="ts">

const vFocus = {
  // 组件挂载完成后调用
  mounted: (el: any, binding: any) => {
    el.focus()
  }
}

</script>

<template>
  <input v-focus/>
</template>
<!--src/App.vue-->
<script setup lang="ts">

const vFocus = {
  mounted: (el: HTMLElement, binding: any) => {
    // 指令绑定的元素
    console.log(typeof el);
    console.log(el);
    // 指令绑定的参数
    console.log(binding)

    // 如果是输入框
    if (el instanceof HTMLInputElement) {
      // 元素聚焦
      el.focus();
      el.placeholder = '请输入';
      el.value = '勤奋、努力'
    }else if (el instanceof HTMLAnchorElement) {
      // 如果是<a>标签我们就导向 百度翻译
      el.href='https://fanyi.baidu.com/'
    }
  }
}
</script>

<template>
  <input v-focus/>
  <p/>
  <a v-focus href="https://www.baidu.com/">百度一下,你就知道</a>
</template>

温馨提示:上例中的自定义指令绑定el-input是不生效的,因为el-input标签的dom结构首层是div而不是input 。

二、生命周期

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

三、钩子参数

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。
prevNode:之前的渲染中代表指令所绑定元素的 VNode。仅在 beforeUpdate 和 updated 钩子中可用。

四、全局注册

import {createApp} from 'vue'
import App from './App.vue'


const app = createApp(App);

app.directive('focus', {
    mounted: (el: any, binding: any) => {
        el.focus()
    }
})
app.mount('#app');
<script setup lang="ts">

</script>

<template>
  <input v-focus/>
</template>

五、封装鉴权指令

三个指令:权限鉴定角色鉴定按钮防抖

在src下新建directive文件夹并在directive文件夹下新建index.ts;
在到directive文件夹下新建permission文件夹,在permission文件夹下新建index.ts;
在directive文件夹下新建utils文件夹,并在utils文件夹下新建index.ts文件;

// src/directive/permission/index.ts
import { useUserStoreHook } from '@/store/modules/user';
import { Directive, DirectiveBinding } from 'vue';

/**
 * 按钮权限校验
 */
export const hasPerm: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    // 「超级管理员」拥有所有的按钮权限
    const { roles, perms } = useUserStoreHook();
    if (roles.includes('ROOT')) {
      return true;
    }
    // 「其他角色」按钮权限校验
    const { value } = binding;
    if (value) {
      const requiredPerms = value; // DOM绑定需要的按钮权限标识

      const hasPerm = perms?.some(perm => {
        return requiredPerms.includes(perm);
      });

      if (!hasPerm) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error(
        "need perms! Like v-has-perm=\"['sys:user:add','sys:user:edit']\""
      );
    }
  }
};

/**
 * 角色权限校验
 */
export const hasRole: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;

    if (value) {
      const requiredRoles = value; // DOM绑定需要的角色编码
      const { roles } = useUserStoreHook();
      const hasRole = roles.some(perm => {
        return requiredRoles.includes(perm);
      });

      if (!hasRole) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("need roles! Like v-has-role=\"['admin','test']\"");
    }
  }
};
// src/directive/utils/index.ts
import { Directive, DirectiveBinding } from 'vue';

/**
 * 按钮防抖
 */
export const deBounce:Directive = {
  mounted(el:HTMLElement) {
    el.addEventListener('click', e => {
      el.classList.add('is-disabled')
      setTimeout(() => {
        el.classList.remove('is-disabled')
      }, 2000)
    })
  }
}
// src/directive/index.ts
export { hasPerm, hasRole } from './permission';
export { deBounce } from './utils';

使用案例

<!--src/App.vue-->
<script setup lang="ts">

</script>

<template>
  <el-button v-hasPerm="['user:delete']">确认</el-button>
  <el-button >取消</el-button>
</template>

Logo

快速构建 Web 应用程序

更多推荐