一、render函数
在App.vue中有一数组['html','css','js','vue','flutter']欲以指定标签渲染,App.vue中代码如下:
<template>
<div>
<List :data="['html','css','js','vue','flutter']" :render="render"></List>
</div>
</template>
<script>
import List from "./list.vue"
export default {
components: {
List
},
methods: {
render(h, item) {
return <p> {item} </p>
}
}
}
</script>
<style>
</style>
接下来需要创建list.vue组件,进行数据渲染
<template>
<div>
<template v-for="(item,index) in data">
<! 当App.vue不传render函数时,默认使用li渲染出来 ---->
<li v-if="!render" :key="index">{{item}}</li>
<ListItem v-else :item="item" :render="render" :key="index"></ListItem>
</template>
</div>
</template>
<script>
import ListItem from "./listItem.js"
export default {
components: {
ListItem
},
props: {
data: {
type: Array
},
render: {
type: Function
}
}
}
</script>
<style>
</style>
之后可创建listItem.js进行数据处理
export default {
props: {
render: {
type: Function
},
item: {
type: String
}
},
render(h) {
return this.render(h, this.item)
}
}
二、插槽方式
使用插槽的方式则更加简洁优雅
只需要在App.vue中指明需要使用的标签即可
<template>
<div>
<List :data="['html','css','js','vue','flutter']">
<template v-slot="{item}">
<span>{{item}}</span>
</template>
</List>
</div>
</template>
<script>
import List from "./list.vue"
export default {
components: {
List
},
methods: {
}
}
</script>
在list.vue中只需要放置一个插槽接受数据即可
<template>
<div>
<template v-for="(item,index) in data">
<!-- 作用域插槽 -->
<slot :item="item"></slot>
</template>
</div>
</template>
<script>
export default {
props: {
data: {
type: Array
}
}
}
</script>