vue3 全局注册自定义指令,input聚焦失焦展示对应值

简单举例:聚焦大写英文、失焦小写英文

创建一个专门的文件来存放自定义指令,例如 directives/modifyOnFocusBlur.js

TypeScript 复制代码
export const modifyOnFocusBlur = {
  mounted(el: { value: string; dispatchEvent: (arg0: Event) => void; addEventListener: (arg0: string, arg1: { (): void; (): void }) => void; _focusHandler: () => void; _blurHandler: () => void }, binding: { arg: string; modifiers: { required: any }; value: string }) {
    // 聚焦时的处理函数
    const handleFocus = () => {
      // 自定义聚焦时的行为
      if (binding.arg === 'upperlower') {
        el.value = el.value.toUpperCase();
      }
      // 通知 v-model 更新
      el.dispatchEvent(new Event('input'));
    };

    // 失焦时的处理函数
    const handleBlur = () => {
      if (binding.arg === 'upperlower') {
        el.value = el.value.toLowerCase();
      }
      // 通知 v-model 更新
      el.dispatchEvent(new Event('input'));
    };

    // 添加事件监听器
    el.addEventListener('focus', handleFocus);
    el.addEventListener('blur', handleBlur);

    // 保存事件处理函数引用,以便后续移除
    el._focusHandler = handleFocus;
    el._blurHandler = handleBlur;
  },

  beforeUnmount(el: { removeEventListener: (arg0: string, arg1: any) => void; _focusHandler: any; _blurHandler: any }) {
    // 移除事件监听器,防止内存泄漏
    el.removeEventListener('focus', el._focusHandler);
    el.removeEventListener('blur', el._blurHandler);
    delete el._focusHandler;
    delete el._blurHandler;
  },
};

全局注册指令

TypeScript 复制代码
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import { modifyOnFocusBlur } from './directives/modifyOnFocusBlur';

const app = createApp(App);

// 全局注册自定义指令
app.directive('modify-on-focus-blur', modifyOnFocusBlur);

app.mount('#app');

在组件中使用自定义指令

TypeScript 复制代码
<input v-model="message" v-modify-on-focus-blur:upperlower placeholder="输入内容">
相关推荐
TT哇2 小时前
【实习 】银行经理端两个核心功能的开发与修复(银行经理绑定逻辑修复和线下领取扫码功能开发)
java·vue.js
星光不问赶路人4 小时前
vue3使用jsx语法详解
前端·vue.js
weixin79893765432...4 小时前
Vue 组件的更新过程(编译系统 + 响应式系统 + 虚拟 DOM & Diff)
vue.js
我是伪码农5 小时前
Vue 智慧商城项目
前端·javascript·vue.js
小书包酱6 小时前
在 VS Code中,vue2-vuex 使用终于有体验感增强的插件了。
vue.js·vuex
Zhencode6 小时前
Vue3 响应式依赖收集与更新之effect
前端·vue.js
天下代码客7 小时前
使用electronc框架调用dll动态链接库流程和避坑
前端·javascript·vue.js·electron·node.js
weixin79893765432...8 小时前
Vue 渲染体系“三件套”(template 模板语法、h 函数和 JSX 语法)
vue.js·h函数·template 模板·jsx 语法
xkxnq8 小时前
第五阶段:Vue3核心深度深挖(第74天)(Vue3计算属性进阶)
前端·javascript·vue.js
Hilaku8 小时前
不要在简历上写精通 Vue3?来自面试官的真实劝退
前端·javascript·vue.js