插槽在vue里面也是可以数据通信的,但是很多人却忽略了这个!今天我们研究一下slot的使用方法!
<Lists :datas="['奶茶', '水果', '披萨']"></Lists>
<Lists :datas="['苹果', '香蕉', '橘子']" :render="render"></Lists>
<hr />
<Lists1 :datas="['苹果', '香蕉', '橘子']">
<template #a="obj">
<!-- 具名插槽的写法 -->
<!-- <template v-slot:a= -->
<span>{{ obj.item }}</span>
</template>
</Lists1>
import Lists from "../components/Lists";
import Lists1 from "../components/Lists1";
export default {
components: {
Lists,
Lists1,
},
methods: {
render(h, data) {
return <span>{data}</span>;
},
},
};
</script>
List.vue
<template>
<div>
<template v-for="(item, index) in datas">
<li :key="index" v-if="!render">
{{ item }}
</li>
<ListItem
v-else
:item="item"
:key="`a${index}`"
:render="render"
></ListItem>
</template>
</div>
</template>
<script>
import ListItem from "./ListsItem";
export default {
props: {
datas: {
type: Array,
default: () => [],
},
render: {
type: Function,
},
},
components: {
ListItem,
},
};
</script>
<style lang="scss" scoped></style>
listItem.vue
export default {
props: {
render: {
type: Function,
},
item: {
type: String,
},
},
render(h) {
console.log(h);
return this.render(h, this.item);
},
};
lists1.vue
<template>
<div>
<template v-for="(item, index) in datas">
<li :key="index" v-if="!render">
<slot name="a" :item="item" :a="index"></slot>
</li>
<ListItem
v-else
:item="item"
:key="`a${index}`"
:render="render"
></ListItem>
</template>
</div>
</template>
<script>
import ListItem from "./ListsItem";
export default {
props: {
datas: {
type: Array,
default: () => [],
},
render: {
type: Function,
},
},
components: {
ListItem,
},
};
</script>
<style lang="scss" scoped></style>
这样就是插槽在组件中的使用方法!