【vue3】vue3 setup如何使用render渲染函数?

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的一切疑问,大家可以在评论区留言提问。

上一篇:vue3 setup如何使用router和route?
下一篇:vue3 setup父组件如何调用子组件方法?

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值