Vue3 中 jsx 语法的自定义指令和函数方法如何在Typescript 和Javascript 中去使用

前言

1.在今年九月份时写过一篇 Three.js实现一个3D模型可视化编辑系统 主要是和大家分享了一下自己如何实现这个3d模型编辑器的过程和项目内容,文章也非常有幸被掘金推荐到首页。

2.该项目也在git上收获了许多的star,因为之前是用Vue3+Javascript实现的,由于最近也学习了Typescript的使用,于是决定对该项目进行Vue3+Typescript分支的版本重构。

3.在整个项目的重构过程中也发现很多相同的方法在Typescript中使用差异非常的大。

4.今天主要给大家分享一下 vue3自定义指令和函数方法在jsx语法中 TypescriptJavascript 的用法区别。

首先我们先看 jsx语法的一些属性在 Javascript 中如何去写

在render + h 函数里面实现一个带有id属性和自定义指令的div元素

 render(){
  return h(<div v-zLoading={loading} 
       onClick={()=>{
          console.log(‘这是一个点击事件’)
       }}
      style={{
       width: width - 10 + 'px',
       height: height - 10 + 'px',
       pointerEvents: 'none' }} 
       id={elementId} >
    </div>)
 }

这就是jsx语法在Vue3+js中去实现的写法,然而同样的代码复制粘贴到Typescript中去就会出现ts的语法警告(大概意思就是说ts不支持这种语法)。

在查阅了Vue3官网文档等相关资料后,发现Typescript的jsx语法中的自定义指令需要通过Vue3新增的 resolveDirective 和 withDirectives 这两个函数来配合实现

而函数方法则是需要通过 withModifiers 函数来实现

同样的内容在 Typescript中如何编写

1.首先引入 withDirectives, resolveDirective ,withModifiers 三个方法

2.通过 resolveDirective 获取到已经注册的自定义指令

3.通过 withDirectives 创建带有自定义指令的元素

4.通过 withModifiers 来定义一个点击事件函数方法

import {  h, withDirectives, resolveDirective } from 'vue'
render(){
          const zLoading = resolveDirective('zLoading')
          
   	return withDirectives(h('div', {
                  onClick:withModifiers(()=>{
                        console.log(‘这是一个点击事件’)
                   },['stop','prevent']),       
	                style: {
			    width: width - 10 + 'px',
			    height:height - 10 + 'px',
			    pointerEvents: 'none',
			},
		           id: elementId,
		       }), [
			  [zLoading, loading]
		     ])
      }
        

关于 resolveDirective , withDirectives ,withModifiers

1.resolveDirective :按名称手动解析已注册的指令。

  • 类型

     function resolveDirective(name: string): Directive | undefined
    

详细信息:为了能从正确的组件上下文进行解析,resolveDirective() 必须在setup() 或渲染函数内调用。
如果指令没有找到,会抛出一个运行时警告,并返回 undefined

2.withDirectives : 用于给 vnode 增加自定义指令。

  • 类型
function withDirectives( vnode: VNode, directives: DirectiveArguments ): VNode

type DirectiveArguments = Array< 
 | [Directive] 
 | [Directive, any] 
 | [Directive, any, string] 
 | [Directive, any, string, DirectiveModifiers] 
>

详细信息:用自定义指令包装一个现有的 vnode。第二个参数是自定义指令数组。每个自定义指令也可以表示为 [Directive, value, argument, modifiers] 形式的数组。如果不需要,可以省略数组的尾元素。

3.withModifiers:用于向事件处理函数添加内置 v-on 修饰符

  • 类型
   function withModifiers(fn: Function, modifiers: string[]): Function

4.内容参考自Vue3官方文档:渲染函数API

以上就是我个人总结出的 Vue3 jsx语法自定义指令和函数方法在Typescript和Javascript 的使用异同,如有错误欢迎指正^_^

完整的代码可以参考:

js版本:gitee.com/ZHANG_6666/… 767-810 行代码

ts版本:gitee.com/ZHANG_6666/… 808-877 行代码

原文链接:https://juejin.cn/post/7313048219302641691 作者:答案answer

(0)
上一篇 2023年12月17日 上午10:16
下一篇 2023年12月17日 上午10:26

相关推荐

发表回复

登录后才能评论