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一定要有二个单引号引起来,否则不生效,实测生效。

相关推荐
洋洋技术笔记39 分钟前
计算属性与侦听器
前端·vue.js
李剑一1 小时前
拿来就用!Vue3+Cesium 飞入效果封装,3D大屏多场景直接复用
前端·vue.js·cesium
Forever7_17 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码117 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial17 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
SuperEugene19 小时前
Vue状态管理扫盲篇:如何设计一个合理的全局状态树 | 用户、权限、字典、布局配置
前端·vue.js·面试
阿懂在掘金19 小时前
defineModel 是进步还是边界陷阱?双数据源组件的选择逻辑
vue.js·源码阅读
李剑一19 小时前
要闹哪样?又出现了一款新的格式化插件,尤雨溪力荐,速度提升了惊人的45倍!
前端·vue.js
阿虎儿20 小时前
React Context 详解:从入门到性能优化
前端·vue.js·react.js
滕青山1 天前
文本行过滤/筛选 在线工具核心JS实现
前端·javascript·vue.js