Vue 自定义指令的使用场景

了解 Vue 自定义指令的概念和常见应用场景

问题

Vue 中的自定义指令是什么?有哪些实际应用场景?

解答

自定义指令(Custom Directive)是 Vue 提供的一种扩展模板语法的机制,允许你在 DOM 元素上添加自定义行为,并在元素的生命周期(插入、更新、移除)中执行特定操作。

定义方式

通过 Vue.directive 函数定义,接收指令名称和包含钩子函数的选项对象:

// 全局注册
Vue.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

// 组件内注册
export default {
  directives: {
    focus: {
      mounted(el) {
        el.focus()
      }
    }
  }
}

常见应用场景

1. DOM 操作

直接操作元素的样式、属性或事件:

Vue.directive('highlight', {
  mounted(el, binding) {
    el.style.backgroundColor = binding.value
  }
})

// 使用:<div v-highlight="'yellow'">高亮文本</div>

2. 表单验证

监听输入变化并实时验证:

Vue.directive('validate', {
  mounted(el, binding) {
    el.addEventListener('input', (e) => {
      const isValid = binding.value.test(e.target.value)
      el.style.borderColor = isValid ? 'green' : 'red'
    })
  }
})

// 使用:<input v-validate="/^\d+$/" />

3. 权限控制

根据用户权限控制元素显示:

Vue.directive('permission', {
  mounted(el, binding) {
    const hasPermission = checkUserPermission(binding.value)
    if (!hasPermission) {
      el.style.display = 'none'
    }
  }
})

// 使用:<button v-permission="'admin'">删除</button>

4. 第三方库集成

封装第三方库的初始化逻辑:

Vue.directive('chart', {
  mounted(el, binding) {
    const chart = new Chart(el, binding.value)
  },
  unmounted(el) {
    // 清理资源
  }
})

// 使用:<div v-chart="chartOptions"></div>

5. 动画效果

配合 Vue 过渡系统实现自定义动画:

Vue.directive('fade', {
  mounted(el) {
    el.style.opacity = 0
    el.style.transition = 'opacity 0.5s'
    setTimeout(() => el.style.opacity = 1, 0)
  }
})

// 使用:<div v-fade>淡入内容</div>

关键点

  • 自定义指令用于封装可复用的 DOM 操作逻辑
  • 通过钩子函数(mounted、updated、unmounted 等)控制指令行为
  • 适合处理底层 DOM 操作、第三方库集成和权限控制等场景
  • 避免在指令中处理复杂业务逻辑,保持指令职责单一
  • Vue 3 中钩子函数名称有变化(bind → beforeMount,inserted → mounted 等)