学习本章节之前可以查阅一下 JSX基本语法及使用 这篇文章,学习一下JSX的基本使用
以及 如何在VUE3项目中使用TSX 这篇文章,了解如何在项目中使用TSX编写组件
Vue3使用TSX的方式
第一种方式:返回一个渲染函数
// src/App.tsx
export default function() {
return (
<div>
小张
</div>
)
}
可以在页面中直接导入使用
// app.vue中使用
<template>
<div>
<AppTsx></AppTsx>
</div>
</template>
<script setup lang="ts">
import AppTsx from './App'
</script>
第二种方式:optionApi模式
// src/App.tsx
import { defineComponent } from 'vue'
export default defineComponent({
data() {
return {
name: '小张'
}
},
render() {
return (
<div>{this.name}</div>
)
}
})
可以在页面中直接导入使用
// app.vue中使用
<template>
<div>
<AppTsx></AppTsx>
</div>
</template>
<script setup lang="ts">
import AppTsx from './App'
</script>
第三种方式:setup模式
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
const name = '小张'
return () => (
<div>
{name}
</div>
)
}
})
Vue3使用TSX的语法
可以使用 v-model
注意 : 使用ref定义变量时,ref在template中会自动解包,在tsx中是不会的,需要用.value
import { ref } from 'vue'
let v = ref<string>('')
export default () => {
return (
<>
<input v-model={v.value} type="text" />
<div>
{v.value}
</div>
</>
)
}
无法使用v-if 使用 三元表达式代替或者使用 if 语句
import { ref } from 'vue'
let flag = ref(false)
export default () => {
return (
<>
{
flag.value ? <div>true</div> : <div>false</div>
}
</>
)
}
使用 if 语句
import { ref } from 'vue'
let flag = ref(false)
export default () => {
const element = null
if(flag.value) {
element = <div>true</div>
} else {
element = false
}
return element
}
可以使用 v-show
import { ref } from 'vue'
let flag = ref(false)
export default () => {
return (
<>
<div v-show={flag.value}>true</div>
<div v-show={!flag.value}>false</div>
</>
)
}
无法使用v-for 使用 map()方法代替
可以使用 map()方法来返回标签
import { ref } from 'vue'
let arr = [1,2,3,4,5]
export default () => {
return (
<>
{
arr.map(v=>{
return <div>${v}</div>
})
}
</>
)
}
可以使用 v-bind
直接对属性进行{}赋值即可
import { ref } from 'vue'
let id = ref('my')
export default () => {
return (
<>
<div id={id}>true</div>
</>
)
}
v-on 事件绑定
事件绑定按照 react的风格书, 即:
- 所有事件用
on开头 - 所有事件名称首字母大写
const handleClick = () => {
console.log('click');
}
export default () => {
return (
<>
<button onClick={handleClick}>按钮</button>
</>
)
}
props 接收参数
import { ref } from 'vue'
type Props = {
params: string
}
export default (props: Props) => {
return (
<>
<div>{props.params}</div>
</>
)
}
emit 派发事件
import { ref } from 'vue'
type Props = {
params: string
}
const handleClick = (context: any) => {
context.emit('onClick', '点击')
}
export default (props: Props, context: any) => {
return (
<>
<div>{props.params}</div>
<button onClick={handleClick.bind(this, context)}>点击</button>
</>
)
}
slot 插槽
定义插槽
const Component = (props, { slots }) => (
<>
<h1>{ slots.default ? slots.default() : '默认显示' }</h1>
<h2>{ slots.bar?.() }</h2>
</>
)
export default Component
使用插槽
const App = {
setup() {
const slots = {
default: () => <div>把默认显示的替换掉</div>,
bar: () => <span>B</span>
}
return () => (
<A v-slots={slots}>
<div>A</div>
</A>
)
}
}