vue的插槽的使用
1:普通插槽
先写一个slot的插槽 占位
<template>
<div>
<slot>
<h1>{{ title }}</h1>
</slot>
</div>
</template>
<script>
export default {
data() {
return {
}
},
props:['title']
}
</script>
<style lang="less" scoped>
</style>
然后再在app.vue的组件中写内容 就可以展示出来
<template>
<div id="app">
<Slot1 title="名字" >
<ul>
<li v-for="(item, index) in name" :key="index">
{{ item }}
</li>
</ul>
</Slot1>
<Slot1 title="爱好">
<ul>
<li v-for="(item, index) in love" :key="index">
{{ item }}
</li>
</ul>
</Slot1>
</div>
</template>
<script>
import Slot1 from "../src/views/slot1.vue";
export default {
data() {
return {
name: ["zy", "zyq", "cyq"],
love: ["健身", "弹琴", "张艺兴"],
};
},
components: { Slot1 },
};
</script>
<style lang="less" scoped></style>
2:具名插槽
在1的基础上,写两个插槽,并各自取名
<template>
<div>
<slot name="slot1">
<h1>{{ title }}</h1>
</slot>
<slot name="slot2">
</slot>
</div>
</template>
app.vue中
<template>
<div id="app">
<Slot1 title="名字" >
<ul slot="slot1">
<li v-for="(item, index) in name" :key="index">
{{ item }}
</li>
</ul>
<div slot="slot2">这是第二个插槽的内容</div>
</Slot1>
<Slot1 title="爱好">
<ul>
<li v-for="(item, index) in love" :key="index">
{{ item }}
</li>
</ul>
</Slot1>
</div>
</template>
3:作用域插槽
数据放在子组件中 父组件通过一定的方式可以拿到子组件的值并渲染到页面(可以这么理解)
<template>
<div>
<h1>{{ title }}分类</h1>
<slot :mingzi="mingzi"></slot>
</div>
</template>
<script>
export default {
data() {
return {
mingzi: ["zy", "zyq", "cyq"],
}
},
props:['title']
}
</script>
<style lang="less" scoped>
</style>
app.vue中
<template>
<div id="app">
<Slot1 title="名字">
<template scope="aaaaa">
<!-- {{zhangyu.name}} -->
<ul>
<li v-for="(item, index) in aaaaa.mingzi" :key="index">
{{ item }}
</li>
</ul>
</template>
</Slot1>
<Slot1 title="名字">
<template scope="aaaaa">
<!-- {{zhangyu.name}} -->
<ol>
<li v-for="(item, index) in aaaaa.mingzi" :key="index">
{{ item }}
</li>
</ol>
</template>
</Slot1>
</div>
</template>
<script>
import Slot1 from "../src/views/slot1.vue";
export default {
data() {
return {};
},
components: { Slot1 },
};
</script>
<style lang="less" scoped></style>
注:
aaaaa可以随意定义 可以试试输出aaaaa代表的值
最终是app.vue收到了子组件的值,并渲染