1.创建HelloWord.jsx文件
import { defineComponent } from "vue"
const helloWord = defineComponent({
setup() {
return () => (
<>
<div>helloWord</div>
</>
)
}
})
export default helloWord
2.Dom上使用ref变量
import { defineComponent } from "vue"
const helloWord = defineComponent({
setup() {
const account = ref(1)
setInterval(() => {
account.value = account.value + 1
}, 1000)
return () => (
<>
<div>helloWord{account.value}</div>
</>
)
}
})
export default helloWord
3.遍历、条件渲染
import { defineComponent } from "vue"
const helloWord = defineComponent({
setup() {
const list = ["一", "二", "三", "四", "五"]
const show = ref(false)
function onSwitch() {
show.value = !show.value
}
return () => (
<>
<div>
<label>遍历渲染</label>
{/* 遍历渲染 */}
{list.map((item, index) => {
return <li key={index}>{item}</li>
})}
</div>
<div>
<label>条件渲染</label>
{/* 条件渲染 */}
{show.value && <div>helloWord</div>}
{/* 三目运算 */}
{show.value ? <div>helloWord</div> : <div>hide</div>}
</div>
<button onClick={onSwitch}>显示/隐藏文本</button>
</>
)
}
})
export default helloWord
4、事件绑定
(1)简单绑定
import { defineComponent } from "vue"
const helloWord = defineComponent({
setup() {
const show = ref(false)
function onSwitch() {
show.value = !show.value
}
return () => (
<>
<div>
<label>条件渲染</label>
{/* 条件渲染 */}
{show.value && <div>helloWord</div>}
{/* 三目运算 */}
{show.value ? <div>helloWord</div> : <div>hide</div>}
</div>
<button onClick={onSwitch}>显示/隐藏文本</button>
</>
)
}
})
export default helloWord
(2)事件修饰符
对于 .passive
、.capture
和 .once
事件修饰符,可以使用驼峰写法将他们拼接在事件名后面:
<button
onClickCapture={() => {}}
onKeyupOnce={() => {}}
onMouseoverOnceCapture={() => {}}
/>
对于事件和按键修饰符,可以使用 withModifiers 函数:
import { defineComponent } from "vue"
import { withModifiers } from "vue"
const helloWord = defineComponent({
setup() {
return () => (
<>
{/* 等价于 v-on:click.stop.prevent */}
<button onClick={withModifiers(() => {}, ["stop", "prevent"])}>按钮</button>
</>
)
}
})
export default helloWord
5、Class 与 Style 绑定
import { defineComponent } from "vue"
const helloWord = defineComponent({
setup() {
const className = "className"
return () => (
<>
<div class={className}></div>
<div
style={{
background: "red"
}}
>
背景色
</div>
</>
)
}
})
export default helloWord
6、使用自定义组件
import { defineComponent } from "vue"
const helloWord = defineComponent({
setup() {
return () => (
<>
<ButtonCustom count={10} onChange={() => {}} />
</>
)
}
})
export default helloWord