在 Vue3 中优雅的使用 Jsx/Tsx

开发 前端
相信 React 的伙伴对于 Jsx/Tsx 都不陌生吧,现在在 Vue3 中也可以使用 jsx/tsx 语法拉。

前言

相信 react 的伙伴对于 jsx/tsx 都不陌生吧,现在在 vue3 中也可以使用 jsx/tsx 语法拉。

安装插件(@vitejs/plugin-vue-jsx)

vite官方提供了官方的插件来支持在vue3中使用jsx/tsx,直接安装就行。

yarn add @vitejs/plugin-vue-jsx -D

安装完之后在vite.config.ts中插入一下代码。

import vueJsx from "@vitejs/plugin-vue-jsx";
export default defineConfig({
plugins: [
vueJsx(),
]
})

配置完就可以在项目中使用jsx/tsx啦。

1、插值

jsx/tsx 的插值与 vue 模板语法中的插值一样,支持有效的 Javascript表达式,比如:a + b, a || 5...。

只不过在 jsx/tsx中 由双大括号{{}} 变为了单大括号{}。

// vue3模板语法
<span>{{ a + b }}</span>

// jsx/tsx
<span>{ a + b }</span>

2、class与style 绑定

class类名绑定有两种方式,使用模板字符串或者使用数组。

  • 使用模板字符串两个类名之间使用空格隔开。

// 模板字符串
<div className={`header ${ isBg ? 'headerBg' : '' }`}>header</div>
//数组
<div class={ [ 'header', isBg && 'headerBg' ] } >header</div>

style绑定需要使用 双大括号。

const color = 'red'
const element = <sapn style={{ color, fontSize: '16px' }}>style</sapn>

3、条件渲染

  • jsx/tsx中只保留了v-show指令,没有 v-if指令。
  • 使用if/else和三目表达式都可以实现。

setup() {
const isShow = false
const element = () {
if (isShow) {
return <span>我是if</span>
} else {
return <span>我是else</span>
}
}
return () (
<div>
<span v-show={isShow}>我是v-show</span>
{
element()
}
{
isShow ? <p>我是三目1</p> : <p>我是三目2</p>
}
<div>
)
}

4、列表渲染

同样,jsx/tsx 中也没有 v-for指令,需要渲染列表我们只需要使用Js 的数组方法 map 就可以了。

setup() {
const listData = [
{name: 'Tom', age: 18},
{name: 'Jim', age: 20},
{name: 'Lucy', age: 16}
]
return () (
<div>
<div class={'box'}>
<span>姓名</span>
<span>年龄</span>
</div>
{
prop.listData.map(item => {
return <div class={'box'}>
<span>{item.name}</span>
<span>{item.age}</span>
</div>
})
}
</div>
)
}

5、事件处理

  • 绑定事件使用的也是 单大括号{},不过事件绑定不是以 @为前缀了,而是改成了 on,例如:click 事件是 onClick。
  • 如果需要使用事件修饰符,就需要借助withModifiers方法啦,withModifiers 方法接收两个参数,第一个参数是绑定的事件,第二个参数是需要使用的事件修饰符。
setup() {
const clickBox = val {
console.log(val)
}
return () (
<div class={'box1'} notallow={() => clickBox('box1')}>
<span>我是box1</span>
<div class={'box2'} notallow={() => clickBox('box2')}>
<span>我是box2</span>
<div class={'box3'} notallow={withModifiers(() => clickBox('box3'), ['stop'])}>我是box3</div>
</div>
</div>
)
}

6、v-model

jsx/tsx是支持v-model语法的。

// 正常写法
<input v-model="value" /> // vue
<input v-model={value} /> // jsx

// 指定绑定值写法
<input v-model:modelValue="value" /> // vue
<input v-model={[value,'modelValue']} /> // jsx

// 修饰符写法
<input v-model:modelValue.trim="value" /> // vue
<input v-model={[value,'modelValue',['trim']]} /> // jsx

7、slot插槽

定义插槽

jsx/tsx中是没有 slot 标签的,定义插槽需要使用{}或者使用renderSlot函数。

setup 函数默认接收两个参数 1. props 2. ctx 上下文 其中包含 slots、attrs、emit 等。

import { renderSlot } from "vue"
export default defineComponent({
// 从ctx中解构出来 slots
setup(props, { slots }) {
return () (
<div>
{ renderSlot(slots, 'default') }
{ slots.title?.() }
</div>
)
}
})

使用插槽

可以通过 v-slots 来使用插槽。

import Vslot from './slotTem'
export default defineComponent({
setup() {
return () (
<div class={'box'}>
<Vslot v-slots={{
title: () => {
return <p>我是title插槽</p>
},
default: () => {
return <p>我是default插槽</p>
}
}} />
</div>
)
}
})

8、使用 tsx 实现递归组件-菜单

主要功能就是根据路由信息自动取生成菜单。

效果如下:

代码如下,如果需要控制权限啥的,自己在路由信息的meta中添加对应的参数,然后在menuItem中自行控制。

// index.tsx

import { routes } from '@/router/index'
import MenuItem from './menuItem'
import './index.scss'

export default defineComponent({
setup() {
const isShowRoutes = computed(() {
return routes
})
const currentPath = computed(() {
return useRoute().path
})

return () (
<el-scrollbar class={`menuContent`}>
<el-menu
default-active={currentPath.value}
mode="vertical"
class={'menu'}
>
{
isShowRoutes.value.map((route) => {
return <MenuItem item={route} key={route.path}></MenuItem>
})
}
</el-menu>
</el-scrollbar>
)
}
})
// menuItem.tsx

import { defineComponent, PropType } from 'vue'
import { RouteRecordRaw } from 'vue-router'
import './index.scss'

const MenuItem = defineComponent({
name: 'MenuItem',
props: {
item: {
type: Object as PropType<RouteRecordRaw>,
required: true
}
},
setup(props: { item: any }) {
const router = useRouter()
const jumpRoute = (path: string) => {
router.push(path)
}
return () {
let { item } = props
if (item.children) {
const slots = {
title: () {
return <div>
<span>{item.meta.title}</span>
</div>
}
}
return <el-sub-menu index={item.path} v-slots={slots}>
{item.children.map((child: RouteRecordRaw) => {
return <MenuItem item={child} key={child.path}></MenuItem>
})}
</el-sub-menu>
} else {
return <el-menu-item index={item.path} onClick={() => jumpRoute(item.path)}>{item.meta.title}</el-menu-item>
}
}
}
})

export default MenuItem

责任编辑:姜华 来源: 前端YUE
相关推荐

2024-04-16 12:05:27

Vue3前端

2024-02-02 08:33:00

Vue模板性能

2023-06-02 07:32:34

localStorage​监听

2024-04-08 07:28:27

PiniaVue3状态管理库

2024-04-16 07:46:15

Vue3STOMP协议WebSocket

2021-12-08 09:09:33

Vue 3 Computed Vue2

2020-03-25 18:23:07

Vue2Vue3组件

2021-12-01 08:11:44

Vue3 插件Vue应用

2021-11-30 08:19:43

Vue3 插件Vue应用

2021-12-29 07:51:21

Vue3 插件Vue应用

2023-11-28 09:03:59

Vue.jsJavaScript

2024-01-26 08:06:43

2021-01-15 05:16:37

Vue3开源代码量

2021-12-02 05:50:35

Vue3 插件Vue应用

2022-07-20 11:13:05

前端JSONVue3

2024-03-22 08:57:04

Vue3Emoji表情符号

2022-02-18 09:39:51

Vue3.0Vue2.0Script Set

2022-07-26 01:06:18

Vue3自定义指令

2022-08-01 11:41:00

Vue插件

2024-03-21 08:34:49

Vue3WebSocketHTTP
点赞
收藏

51CTO技术栈公众号