Vue3中TSX的用法

补充:(jsx用法)[https://github.com/vuejs/babel-plugin-jsx]

(vue3中渲染函数&JSX)[https://cn.vuejs.org/guide/extras/render-function.html#creating-vnodes]

安装插件

npm i @vitejs/plugin-vue-jsx -D

vite.config.ts配置

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(), vueJsx()],
})

注意:如果遇到项目启动报错问题TypeError: vite.createFilter is not a function的话,说明vite插件与vite版本不一致。解决npm install -D vite@^3

使用方式

返回一个渲染函数

App.tsx

export default function () {return (<div>我是返回一个渲染函数的jsx写法</div>)
}

App.vue

<script setup lang="ts">
import TestJsx from './App'
</script><template><test-jsx />
</template>

optionsApi

App.tsx

import { defineComponent } from 'vue'export default defineComponent({data() {return {name: '渲染函数'}},render() {return (<h1>{this.name}</h1>)}
})

setup函数模式

App.tsx

import { defineComponent } from 'vue'export default defineComponent({setup() {return () => <div>setup模式</div>}
})

基本用法

主要是介绍setup函数模式中 tsx 的用法

在App.tsx中演示示例代码

插值

使用{}单括号,ref在template模式下会自动解包,tsx下不会

export default defineComponent({setup() {const flag = ref('插值')return () => <div>{flag.value}</div>}
})

多个根节点Fragment

export default defineComponent({setup() {const flag = ref('插值')return () => (<><span>哈喽</span><div>{flag.value}</div></>)}
})

动态属性绑定

如果需要绑定多个属性,使用…操作符

export default defineComponent({setup() {const flag = ref('插值')return () => <div name={flag.value}>{flag.value}</div>}
})
export default defineComponent({setup() {const flag = ref('插值')const properties = {a: '属性1',b: '属性2'}return () => <div {...properties}>{flag.value}</div>}
})

指令

  • v-show
export default defineComponent({setup() {const flag = ref(false)return () => <input v-show={flag.value} />}
})
  • v-model
export default defineComponent({setup() {const flag = ref<string>('')return () => (<><input v-model={flag.value} /><p>{flag.value}</p></>)}
})

插槽slot

const otherComp = (props, { slots }) => (<><h1>{ slots.default ? slots.default() : '我是默认插槽' }</h1><h2>{ slots.bar?.() }</h2></>
)export default defineComponent({setup() {const slots = {bar: () => <span>bar 插槽内容</span>}return () => (<otherComp v-slots={slots}><div>新添加的默认内容</div></otherComp>)}
})

或者

export default defineComponent({setup() {const slots = {default: () => <div>新添加的默认内容</div>,bar: () => <span>bar 插槽内容</span>}return () => <otherComp v-slots={slots}></otherComp>}
})

条件渲染

使用if/else,三目运算符,不能使用v-if

export default defineComponent({setup() {const flag = ref(false)return () => <div>{ flag.value ? '我是真的' : '我是假的' }</div>}
})
export default defineComponent({setup() {const flag = ref(false)return () => {const divInfo = () => {if (flag.value) {return (<><p>哈哈</p><div>我是真的</div></>)} else {return <div>我是假的</div>}}return [divInfo()]}}
})

循环

使用map函数

export default defineComponent({setup() {const list = ['哈喽', '小马', '小羊']return () => (<>{ list.map(i => <div>{i}</div>) }</>)}
})

事件绑定

事件绑定需要在事件名前面加上on前缀,onClick与模板中的@click等价

export default defineComponent({setup() {const list = ['哈喽', '小马', '小羊']const fn = () => {console.log('我被点击了')}return () => (<>{ list.map(i => <div onClick={() => fn()}>{i}</div>) }</>)}
})

传值prop和emit

App.tsx

import { defineComponent, ref } from 'vue'interface Props {name?: string
}
export default defineComponent({props: {name: String},emits: ['change-param'],setup(props: Props, { emit }) {const fn = ((para: string) => {console.log('触发了', para)emit('change-param', para)})return () => (<><div>props: {props?.name}</div></>)}
})

App.vue

<script setup lang="ts">
import { ref } from "vue"
import TestJsx from './App'const getParam = (v: string) => {console.log("父组件收到了子组件的数据", v)
}
</script>
<template><test-jsx name="哈喽" @change-param="getParam" />
</template>

Vue3自动引入插件

插件:unplugin-auto-import/vite

vite.config.ts配置

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(), vueJsx(), AutoImport({imports: ['vue'],dts: 'src/auto-import.d.ts'})]}
})

配置完成之后,使用ref,reactive等无须import 导入,可以直接使用。

Vue3中函数式编程:h函数

vue的编写风格主要有template模板方式、JSX/TSX方式、还有函数式编程,用到的是 h 函数。

h函数接收三个参数

  • type:元素的类型
  • propsOrChildren:数据对象,主要表示props,attrs,dom props,class,style,onClick等
  • children:子节点

h函数有多种组合方式

// 除了类型必填以外,其他的参数都是可选的
h('div')
h('div', { id: 'foo' })// attribute 和 property 都能在 prop 中书写
// Vue 会自动将它们分配到正确的位置
h('div', { class: 'bar', innerHTML: 'hello' })// props modifiers such as .prop and .attr can be added
// with '.' and `^' prefixes respectively
h('div', { '.name': 'some-name', '^width': '100' })// 类与样式可以像在模板中一样
// 用数组或对象的形式书写
h('div', { class: [foo, { bar }], style: { color: 'red' } })// 事件监听器应以 onXxx 的形式书写
h('div', { onClick: () => {} })// children 可以是一个字符串
h('div', { id: 'foo' }, 'hello')// 没有 props 时可以省略不写
h('div', 'hello')
h('div', [h('span', 'hello')])// children 数组可以同时包含 vnodes 与字符串
h('div', ['hello', h('span', 'hello')])

示例:包含props、emit传递参数,插槽的使用方法

<template><div><Btn title="我是传递过来的标题" @on-emit-click="getBtn"><template #default>default</template><template #footer>footer</template></Btn></div>
</template><script setup lang="ts">
import { h } from 'vue'
type Prop = {title: string
}const Btn = (props: Prop, ctx: any) => {return h('div',{style: {background: 'red',width: '200px',height: '100px',display: 'flex','flex-direction': 'column','align-items': 'center','justify-content': 'center',},onClick: () => {ctx.emit('on-emit-click', '哈哈哈哈')}},[props?.title,h('div',{style: {color: 'blue'},},ctx.slots.default(),),h('div',{style: {color: 'green'},},ctx.slots.footer(),),],)
}
const getBtn = (str: string) => {console.log(str)
}
</script>

Vue3中TSX和h函数的用法相关推荐

  1. matlab repmate,MATLAB中“repmat”与“cat”函数的用法

    MATLAB中"repmat"与"cat"函数的用法 1. repmat函数 >> z=repmat(5,2,3) z = 5 5 5 5 5 5 ...

  2. C++中有关queue常用函数的用法及其注意要项

    11:C++中有关queue常用函数的用法及其注意要项 #include<bits/stdc++.h> using namespace std; int main(){queue < ...

  3. python中split的用法取第二个分片_python中split()函数的用法

    函数:split() Python中有split()和os.path.split()两个函数,具体作用如下: split():拆分字符串.通过指定分隔符对字符串进行切片,并返回分割后的字符串列表(li ...

  4. mysql timestamp 差值_MySQL中TIMESTAMPDIFF和TIMESTAMPADD函数的用法(两个日期之间的差值)...

    MySQL中TIMESTAMPDIFF和TIMESTAMPADD函数的用法 在应用时,经常要使用这两个函数TIMESTAMPDIFF和TIMESTAMPADD. 一,TIMESTAMPDIFF 语法: ...

  5. python items函数用法,Python中dictionary items()系列函数的用法实例

    本文实例讲述了Python中dictionary items()系列函数的用法,对Python程序设计有很好的参考借鉴价值.具体分析如下: 先来看一个示例: import html # availab ...

  6. python enumerate函数_关于python中enumerate和zip函数的用法及举例

    关于python中enumerate和zip函数的用法及举例 关于enumerate函数: enumerate函数可以同时返回列表或元组等可迭代对象的下标和内容,但实际上,enumerate函数实际返 ...

  7. “约见”面试官系列之常见面试题之第七十六篇之vue-router中的路由钩子函数基本用法 (建议收藏)

    vue-router中的路由钩子函数基本用法 路由钩子函数分为三种类型如下: 第一种:全局钩子函数. router.beforeEach((to, from, next) => { consol ...

  8. python中字符串函数的用法_python中字符串内置函数的用法介绍(代码)

    本篇文章给大家带来的内容是关于python中字符串内置函数的用法介绍(代码) ,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. capitalize() 首字母大写a='somewor ...

  9. linux之getcwd函数解析,Linux 中C语言getcwd()函数的用法

    Linux 中C语言getcwd()函数的用法 先来看该函数的声明: #include char *getcwd(char *buf,size_t size); 介绍: 参数说明:getcwd()会将 ...

最新文章

  1. for循环中执行setTimeout问题(任务队列的问题)
  2. sysbench测试mysql性能(TPS、QPS、IOPS)(重要)
  3. 利用obfuscar对.NET应用进行混淆
  4. Python 获取md5值(hashlib)
  5. 站长如何屏蔽流氓宽带商在你的页面里面强行插入的广告代码
  6. cad填充图案乱理石_CAD图案填充应该这么操作!简单又高效!!!1分钟就能学会...
  7. Java Switch语句及性能剖析(转载补充)
  8. 预算分配Budget Allocation:Morphl-AI的营销科学解决方案(一)
  9. 机器学习入门——numpy与matplotlib的使用简介
  10. web前端实训day06——学子商城登录页面实现
  11. 大牛熬夜整理,京东网易滴滴,天津农行软开java面试题合集,大牛已于上个月入职华为!
  12. c语言实现费诺编码csdn,香农编码 哈夫曼编码 费诺编码的比较
  13. 【学习求职必备】微软亚洲研究院和它的10大AI黑科技
  14. java+sql+用户登录失败,java.sql.SQLException:用户'sa'登录失败
  15. 移动硬盘做pe启动盘
  16. .rvm/gems/ruby-2.4.1@global/gems/cocoapods-1.5.0/lib/cocoapods/executable.rb:89: warning: Insecure
  17. 五个成人必看的故事!
  18. 2022年危险化学品经营单位安全管理人员考题及答案
  19. WRF-Chem 编译fire_emis报错
  20. python3-编程题之商品价格计算器

热门文章

  1. 【UEFI实战】HII之配置
  2. 女子发现前夫外遇索要2000万
  3. 启动手机自带浏览器和手机拨号
  4. 推荐几款性价比高的优盘
  5. spring data mongodb 大数据量查询性能差的原因(20s 优化到2s)
  6. CPU的两种工作状态——系统态和用户态
  7. 美团·北极星开发对接避坑指北(Java)
  8. ubuntu使用问题
  9. 生产者消费者1.0(wait notify)
  10. 上海工商业分时电价机制调整对储能行业项目的影响分析