vue3 自定义指令 directive

1、官方说明:https://cn.vuejs.org/guide/reusability/custom-directives

除了 Vue 内置的一系列指令 (比如 v-modelv-show) 之外,Vue 还允许你注册自定义的指令 (Custom Directives)。

我们已经介绍了两种在 Vue 中重用代码的方式:组件组合式函数。组件是主要的构建模块,而组合式函数则侧重于有状态的逻辑。另一方面,自定义指令主要是为了重用涉及普通元素的底层 DOM 访问的逻辑。

2、案例说明:

新建文件vNameOfDirectiveTest.vue

代码:

复制代码
<script setup>
const vMyDirective = {
  beforeMount: (el) => {
    // 在元素上做些操作
    console.log(el);
    el.style.color = 'red'
    el.style.backgroundColor = 'yellow'
  }
}
</script>
<template>
  <h1 v-my-directive>This is a Heading</h1>
  <div v-color="'red'">This text will be red.</div>
  <input v-focus value="This is a input"></input>
</template>

说明

vMyDirective:局部指令。

v-color,v-focus:全局指令。

复制代码
const app = createApp(App);
// 注册自定义指令
const color = {
  mounted(el, binding) {
    el.style.color = binding.value;
  },
  // 如果需要在更新时也更新颜色,可以添加一个 `updated` 钩子
  // updated(el, binding) {
  //   el.style.color = binding.value;
  // }
};

app.directive("focus", {
  mounted(el) {
    el.focus();
  },
});

// 全局注册自定义指令
app.directive('color', color);

3、注意:

<div v-color="'red'">This text will be red.</div>

这里的v-color="'red'",red一定要有二个单引号引起来,否则不生效,实测生效。

相关推荐
知识分享小能手2 小时前
Vue3 学习教程,从入门到精通,Axios 在 Vue 3 中的使用指南(37)
前端·javascript·vue.js·学习·typescript·vue·vue3
伍哥的传说3 小时前
Mitt 事件发射器完全指南:200字节的轻量级解决方案
vue.js·react.js·vue3·mitt·组件通信·事件管理·事件发射器
一枚小小程序员哈5 小时前
基于Vue + Node能源采购系统的设计与实现/基于express的能源管理系统#node.js
vue.js·node.js·express
一枚小小程序员哈10 小时前
基于Vue的个人博客网站的设计与实现/基于node.js的博客系统的设计与实现#express框架、vscode
vue.js·node.js·express
定栓10 小时前
vue3入门-v-model、ref和reactive讲解
前端·javascript·vue.js
LIUENG11 小时前
Vue3 响应式原理
前端·vue.js
wycode12 小时前
Vue2实践(3)之用component做一个动态表单(二)
前端·javascript·vue.js
wycode13 小时前
Vue2实践(2)之用component做一个动态表单(一)
前端·javascript·vue.js
第七种黄昏13 小时前
Vue3 中的 ref、模板引用和 defineExpose 详解
前端·javascript·vue.js
pepedd86414 小时前
还在开发vue2老项目吗?本文带你梳理vue版本区别
前端·vue.js·trae