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 }]
    ])
  }
}
相关推荐
BumBle30 分钟前
uniapp AI聊天应用技术解析:实现流畅的Streaming聊天体验(基础版本)
前端·uni-app
搞个锤子哟33 分钟前
vant4的van-pull-refresh里的列表不在顶部时下拉也会触发刷新的问题
前端
jnpfsoft34 分钟前
低代码视图真分页实操:API/SQL 接口配置 + 查询字段避坑,数据加载不卡顿
前端·低代码
HHHHHY34 分钟前
使用阿里lowcode,封装SearchDropdown 搜索下拉组件
前端·react.js
前端付豪35 分钟前
万事从 todolist 开始
前端·vue.js·前端框架
小胖霞36 分钟前
从零开始:在阿里云 Ubuntu 服务器部署 Node+Express 接口(基于公司 GitLab)
前端·后端
A_Bin38 分钟前
前端工程化之【包管理器】
前端
小肚肚肚肚肚哦40 分钟前
CSS 伪类函数 :where 简介
前端·css
Nick568341 分钟前
Swift -- 第三方登录之微信登录 源码分享
前端
麦麦大数据1 小时前
D026 vue3+django 论文知识图谱推荐可视化系统 | vue3+vite前端|neo4j 图数据库
前端·django·vue3·知识图谱·推荐算法·论文文献·科研图谱