[Vue @Component] Control Template Contents with Vue's Render Function

本文探讨了VueJS中模板和元素的声明方式,并深入介绍了如何使用渲染函数和JSX来实现更精细的组件控制。通过一个具体示例,展示了如何在父组件中传递属性和子元素给子组件Content,并在子组件中使用lodash的shuffle函数随机展示图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Declaring templates and elements inside of templates works great for most scenarios. Sometimes you need a bit more control over what your component will do with the props and children it receives, so Vue provides a render function that allows you complete programmatic control over every argument using JSX.

 

We have a parent component which renders:

        <Content slot="content" :limit="4">
            <div><img src="https://robohash.org/mindy?set=set4" alt=""></div>
            <div><img src="https://robohash.org/john?set=set4" alt=""></div>
            <div><img src="https://robohash.org/kim?set=set4" alt=""></div>
            <div><img src="https://robohash.org/joel?set=set4" alt=""></div>
            <div><img src="https://robohash.org/maggie?set=set4" alt=""></div>
        </Content>

 

Content.vue:

<script>
import { shuffle } from "lodash"
export default {
  functional: true,
  render: (createElement, { children, props, data }) => {
    if(props.limit) {
        return createElement('div', data, shuffle(children.slice(0, props.limit)));
    } else {
        return createElement('div', data, shuffle(children));
    }
  }
}
</script>

 

You can also using JSX:

 

转载于:https://www.cnblogs.com/Answer1215/p/9362981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值