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 }]
    ])
  }
}
相关推荐
Mike_jia22 分钟前
uuWAF:开源Web应用防火墙新标杆——从工业级防护到智能防御实战解析
前端
掘金安东尼32 分钟前
Chrome 17 岁了——我们的浏览器简史
前端·javascript·github
袁煦丞32 分钟前
群晖NAS FTP远程文件仓库全球访问:cpolar内网穿透实验室第524个成功挑战
前端·程序员·远程工作
前端小巷子36 分钟前
JS 打造动态表格
前端·javascript·面试
excel1 小时前
从卷积到全连接:用示例理解 CNN 的分层
前端
UNbuff_01 小时前
HTML 各种事件的使用说明书
前端·html
Mr. Cao code1 小时前
探索OpenResty:高性能Web开发利器
linux·运维·服务器·前端·nginx·ubuntu·openresty
百思可瑞教育1 小时前
ActiveMQ、RocketMQ、RabbitMQ、Kafka 的全面对比分析
vue.js·分布式·rabbitmq·rocketmq·activemq·北京百思可瑞教育·百思可瑞教育
li35749 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj9 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js