vue3项目如何在render函数中使用自定义指令

一、定义自定义指令

js 复制代码
// directives/inputQuantity.js
const inputQuantity = {
  mounted(el, binding) {
    el.addEventListener('input', (e) => {
      // 验证输入值
      const value = e.target.value
      const min = binding.value?.min || 0
      const max = binding.value?.max || Infinity
      
      if (/^\d*$/.test(value)) {
        let numValue = parseInt(value) || min
        
        // 限制范围
        if (numValue < min) numValue = min
        if (numValue > max) numValue = max
        
        // 更新模型值
        binding.instance[numValue] = numValue
        el.value = numValue
      } else {
        el.value = binding.value?.lastValid || min
      }
      
      binding.value.lastValid = el.value
    })
  }
}

export default inputQuantity

二、注册指令

全局注册(main.js):

js 复制代码
import { createApp } from 'vue'
import inputQuantity from './directives/inputQuantity'

const app = createApp(App)
app.directive('input-quantity', inputQuantity)

组件内注册:

js 复制代码
import inputQuantity from './directives/inputQuantity'

export default {
  directives: {
    'input-quantity': inputQuantity
  },
  // ...
}

三、在 render 函数中使用自定义指令

在 render 函数中使用指令需要用到vue的两个内部函数 resolveDirectivewithDirectives;

resolveDirective用于解析指令;

withDirectives函数把指令注册对应的VNode对象上

js 复制代码
import { h, withDirectives, resolveDirective } from 'vue'

export default {
  render() {
    // 解析自定义指令
    const vInputQuantity = resolveDirective('input-quantity')
    
    // 创建基础 input 节点
    const inputNode = h('input', {
      type: 'number',
      value: this.quantity,
      class: 'quantity-input'
    })
    
    // 应用自定义指令
    return withDirectives(inputNode, [
      [
        vInputQuantity, 
        { 
          min: 1, 
          max: 100,
          lastValid: 1
        }
      ],
      // 可同时添加其他指令
      ```
      [resolveDirective('focus'), { autoFocus: true }]
    ])
  }
}
相关推荐
人工智能培训4 分钟前
大语言模型:从语言理解到通用智能的跃迁
linux·服务器·前端·人工智能
一拳不是超人14 分钟前
做独立开发三个月,我的第一个产品终于有了 1000 个用户
前端·程序员
Amos_Web24 分钟前
Rspack 源码解析(十):Hash 与 Asset 生成
前端·rust·源码阅读
福兮说26 分钟前
用 IndexedDB 存用户的文件,我踩过的五个坑
前端·javascript
闪耀之光M7827 分钟前
前端依赖自动导入:unplugin-auto-import
前端
Ricon组态薄荷糖41 分钟前
Ricon组态系统:工业组件开发指南与实践
前端·后端·物联网
flash俊杰1 小时前
Electron 桌面应用的进程模型:为什么 fork Next.js standalone
前端
沙蒿同学1 小时前
我把架构约定编译成了会变红的测试:Wails v2 + Go + Vue3 桌面脚手架实战
前端·后端·github
cpolar技术支持1 小时前
本地 Playwright 测试报告怎么远程复盘?Trace Viewer 跑起来后,用 cpolar 分享失败现场
前端·自动化测试·测试工具·cpolar·playwright
wordbaby1 小时前
企业级后台管理系统路由设计与最佳实践指南
前端