安装插件
"@vitejs/plugin-vue-jsx": "^3.1.0" === "vite": "3.0.0",
yarn add @vitejs/plugin-vue-jsx -D
vite配置
import vueJsx from '@vitejs/plugin-vue-jsx' // 添加这一句
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx() // 添加这一句
]
})
设置tstsconfig.json
"compilerOptions": {
"jsx": "preserve",
}
第一种写法
test.jsx
import { defineComponent, ref } from "vue";
const TestJsx = defineComponent({
emits: ['click', 'getDate'],
setup(props, {emit}) {
const val = ref('this is a input');
const userName = ref('this is a username');
const handleInputChange = (e) => { val.value = e.target.value }
const handleClick = () => {
alert("this is a button")
emit("click")
}
const vnode = <div>hello, {userName.value}</div>
const list = [1, 2, 3]
return () => <>
<div>{val.value}</div>
{list.map(item => <div onclick={handleClick}>{item}</div>)}
{vnode}
</>
}
})
export default TestJsx
import { defineComponent, ref } from "vue";
import { ElButton } from 'element-plus'
const TestJsx = defineComponent({
// emits: ['click', 'getDate'],
setup(props, { emit }) {
const shakeList = [
"hvr-bounce-to-bottom",
"hvr-curl-top-left",
"hvr-overline-from-center",
"hover-underline-reverse",
"animate__animated animate__hinge",
"animate__animated animate__jackInTheBox",
"animate__animated animate__zoomInDown",
"animate__animated animate__flipInY"
]
const inputName = ref("xxx")
const changeName = (e) => {
inputName.value = e.target.value
console.log(inputName)
}
const size = ref < 'default' | 'large' | 'small' > ('default')
const value2 = ref('')
const shortcuts = [
{
text: 'Today',
value: new Date(),
},
{
text: 'Yesterday',
value: () => {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24)
return date
},
},
{
text: 'A week ago',
value: () => {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
return date
},
},
]
const disabledDate = (time) => {
return time.getTime() > Date.now()
}
const changeDate = () => {
console.log(value2.value)
}
return () => <>
<div>
{shakeList.map(item => <div><button className={item}>{item}</button></div>)}
</div>
<div>
<el-button type="primary">{inputName.value}</el-button>
<input value={inputName.value} onChange={(e) => changeName(e)} style="width: 240px" placeholder="Please input" />
<el-input v-model={inputName.value} style="width: 240px" placeholder="Please input" />
<el-date-picker
v-model={value2.value}
type="date"
placeholder="Pick a day"
disabled-date={disabledDate}
shortcuts={shortcuts}
size={size.value}
onChange={changeDate}
value-format="YYYY-MM-DD"
/>
</div>
</>
},
})
export default TestJsx
第二种写法
test.vue
// render.vue <script lang="jsx"> import { ref } from "vue"; import { defineComponent } from 'vue' export default { setup() { const count = ref(100); return () => <div>count is: {count.value}</div>; }, }; </script>
在实现业务需求的时候,优先使用 template,尽可能地利用 Vue 本身的性能优化。而对于动态性要求较高的组件可以使用 JSX 来实现。(比如后面,我会用JSX来实现动态表单生成器)
今ならできます。