1. 函数式组件
export default () => <div>test</div>
2. defineComponent
export default defineComponent({
render() {
return <div>tset</div>
}
})
3. defineComponent + setup
摒弃 this ,对于ts支持最好,借助 babel-plugin-jsx
import { defineComponent, withModifiers, ref } from 'vue'
export default defineComponent({
directives: {
focus: {
mounted(el) {
el.focus()
}
}
},
emits: ['click']
setup (props, { slots, emit }) {
const count = ref(0)
const inc = () => {
count.value++
emit('click')
}
const list = ref<string[]>(['a', 'b', 'c'])
return () => { // 这个函数理解为渲染函数,在其中返回最终想要返回的东西
v-if
const span = true ? <span>A</span> : <span>B</span>
return <div onClick => {withModifiers(inc, ['self'])}>
test: {count.value}
<input type="text" v-focus v-model={count.value} />
<div>{ span } </div>
<ul>
{list.value.map((str) => <li key={str}>{str}</li>)}
</ul>
{/* 默认插槽内容 */}
<div>{ slots.default ? slots.default() : 'default content' }</div>
<div>{ slots.title ? slots.title() : 'title slot content' }</div>
{/* <Test v-slot={{
title: () => <h3>title</h3>
}}>abc</Test> */}
</div>
}
}
})