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 }]
    ])
  }
}
相关推荐
c***V3233 小时前
Vue优化
前端·javascript·vue.js
李@十一₂⁰5 小时前
HTML 特殊字体符号
前端·html
小奶包他干奶奶7 小时前
Webpack学习——Loader(文件转换器)
前端·学习·webpack
zy happy7 小时前
若依 vue3 报错:找不到模块“@/api/xxxx/xxxxx”或其相应的类型声明。。Vue 3 can not find mod
前端·javascript·vue.js
潘小安7 小时前
Git Worktree + Claude Code:让你的开发效率翻倍的秘密武器
前端
meichaoWen8 小时前
【Vue3】vue3的全面学习(一)
前端·javascript·学习
小猪努力学前端8 小时前
在 React + React Router v7 SSR 项目里做多端适配,我踩的两个坑
前端·react.js
q***d1738 小时前
React桌面应用开发
前端·react.js·前端框架
8***29318 小时前
解决 Tomcat 跨域问题 - Tomcat 配置静态文件和 Java Web 服务(Spring MVC Springboot)同时允许跨域
java·前端·spring
0***148 小时前
React计算机视觉应用
前端·react.js·计算机视觉