安裝插件
npm i @vitejs/plugin-vue-jsx
vite.config.js
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [vueJsx()],
})
使用jsx
src/App.jsx
import { defineComponent } from 'vue'
export default defineComponent({
name:'App',
setup:(props,ctx) => {
return () => <div>Hello World</div>;
}
})
直接輸出
const com1 = ()=><div>com1</div>;
const com2 = ()=><div>com2</div>;
export default () =>{
return <div>
<com1/>
<com2/>
</div>
}
插值
import { defineComponent,ref } from 'vue';
export default defineComponent({
name: 'App',
setup: (props,ctx)=> {
const text = ref('hello world')
return () => <div>222 {text.value} </div>
}
})
條件渲染和列表
import { defineComponent,ref } from 'vue'
export default defineComponent({
name: 'App',
setup:(props,ctx)=>{
const text = ref('hello world')
const isShow = ref(true)
const list = ['one','two','three','four']
return ()=><div>
{text.value}
{isShow.value?<div>yes</div>:<div>no</div>}
<div v-show={isShow.value}>show</div>
{list.map((item,index)=>{return <div key={index}>{item}-{index}</div>})}
</div>
}
})
事件綁定
import { defineComponent,withModifiers } from "vue"
export default defineComponent({
name: 'App',
setup: (props,ctx)=>{
return () =>
<div>
{/* 兩種事件綁定 */}
{/* <div onClick={withModifiers(()=>{
console.log('點擊了1')
},["self"])}>點擊1</div> */}
{/* 對于 .passive .capture 和 .one 事件修飾符顶滩,使用withModifiers并不生效,這里可以采用鏈式駝峰的形式進行設置 */}
<div onClickOnce={()=>{console.log('點擊了2')}}>點擊2</div>
</div>
}
})
v-model
// 在當組件中使用自定義時間的時候 和 SFC 就有了區(qū)別,比如綁定一個msg,在SFC中直接v-model:msg即可,
// 而在jsx中則需要使用一個數(shù)組按价,例如組件名叫ea_button
// 這個組件發(fā)送一個update:changeMsg的方法,父組件的msg變量需要接受update:changeMsg函數(shù)傳來的參數(shù)
// <ea-button v-model:changeMsg="msg"></ea-button> sfc
// <ea-button v-model={[msg:value,'changeMsg']}></ea-button> jsx
import { defineComponent,ref } from "vue"
export default defineComponent({
name: 'App',
setup:(props,ctx)=>{
const val = ref(1)
return ()=><div>
<input type="text" v-model={val.value} />
{val.value}
</div>
}
})
插槽
// 插槽
import { defineComponent } from "vue"
// 默認插槽
const Child = (props,{slots}) =>{
return <div>{slots.default()}</div>
}
// 具名插槽
const lotChild = (props,{slots})=>{
return (
<div>
<div>{slots.slotOne()}</div>
<div>{slots.slotTwo()}</div>
<div>{slots.slotThree()}</div>
</div>
)
}
// 作用域插槽
const spaceChild = (props,{slots})=>{
const params = '插槽1'
return <div>{slots.slotOne(params)}</div>
}
export default defineComponent({
name:'App',
setup:()=>{
return ()=>(
<div>
<Child>默認插槽</Child>
<lotChild>
{{
slotOne: () => <div>slotOne</div>,
slotTwo: () => <div>slotTwo</div>,
slotThree: () => <div>slotThree</div>
}}
</lotChild>
<spaceChild>{{slotOne:(params)=><div>{params}</div>}}</spaceChild>
<div>222</div>
</div>
)
}
})