setup
是一个组件选项,在组件被创建之前,props
被解析之后执行。它是组合式 API
的入口。
他接受两个参数:
{Data} props
{SetupContext} context
注意:setup
语法糖是不可以使用render
的,所以只有用setup
选项才可以。
<script setup lang="ts">
//这里不能使用render渲染
</script>
我们可以在setup
选项里直接return ()=> h()
或者多个return ()=> [h(),h()]
,不用再写render
了:
<script lang="ts">
import { h,ref,renderSlot,reactive} from 'vue'
import Hello from './hello.vue'
interface listData {
id:number,
text:string
}
export default {
components:{Hello},
setup(){
function changeCount(){
count.value++
}
const count = ref(0)
const list = reactive<listData[]>([
{
id:1,
text:"hahaha"
},
{
id:2,
text:"hehehe"
},
{
id:3,
text:"kokokoko"
},
])
return ()=> [
h("div",{className:"counter test"},count.value),//这里的class要用className
h("button",{onClick:changeCount},"按钮"),//事件的绑定
h("ul",list.map((item:listData)=>{//循环渲染
return h("li",item.text)
})),
h(Hello)//渲染导入的组件
]
}
}
</script>
如果返回了渲染函数,则不能再返回其他 property
。如果需要将 property
暴露给外部访问,比如通过父组件的 ref
,可以使用 expose
:
<script lang="ts">
import { h,ref,renderSlot,reactive} from 'vue'
import Hello from './hello.vue'
interface Data {
[key: string]: unknown
}
interface SetupContext {
//其他属性省略
expose: (exposed?: Record<string, any>) => void
}
setup(props:Data ,{ expose }:SetupContext){
function sayhello(){
console.log("Hello world!")
}
expose({
sayhello
})
return ()=> h(Hello)
//其他代码同上,省略
}
</script>
这时父组件就可以通过ref
调用这个sayhello
函数了。
有帮助的话,点个赞呗!关于vue3的一切疑问,大家可以在评论区留言提问。