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 }]
    ])
  }
}
相关推荐
知心宝贝几秒前
写了那么久的前端,你真的了解浏览器背后的“小动作“吗?
前端·程序员·浏览器
wycode几秒前
Vue2实践(2)之用component做一个动态表单(一)
前端·javascript·vue.js
维李设论2 分钟前
前端智能化 | AG-UI实践及原理浅析
前端·aigc·agent
第七种黄昏2 分钟前
Vue3 中的 ref、模板引用和 defineExpose 详解
前端·javascript·vue.js
一只卡比兽3 分钟前
动态规划与贪心算法详解:原理、对比与代码实践
前端
aiwery6 分钟前
一文掌握 TypeScript 工具类型:Record、Partial、Omit、Pick 等实战用法
前端·代码规范
ankleless20 分钟前
C语言(12)——进阶函数
前端·html
一条上岸小咸鱼24 分钟前
Kotlin 基本数据类型(四):String
android·前端·kotlin
我是哈哈hh38 分钟前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js
张元清1 小时前
电商 Feeds 流缓存策略:Temu vs 拼多多的技术选择
前端·javascript·面试