vue插槽与作用域插槽的演示(前端网备份)
参考https://www.cnblogs.com/ccyinghua/p/7878187.html
然后近一步解释一下作用域插槽
父级组件:
<list2Son :msg="list" @father="change">
<h1 slot="header">这里可能是一个页面标题</h1>
<p>22</p>
<p slot="footer">这里有一些联系信息</p>
<template slot-scope="props">
<ul>
<li v-for="(a,index) in props.text" :key="index">
<!-- 若不加任何判断,整个template中的标签都会替换为定义时的slot -->
<h4>{{a.name}}</h4>
<h5>{{a.age}}</h5>
<!-- 技巧就在于通过a拿到的数据选择性地渲染标签,即修改单个slot对应的作用域范围 -->
<span v-if="a.single">我是单身</span>
<span v-if="a.stu">我是学生</span>
<span v-if="!a.single">我不是单身</span>
<span v-if="!a.stu">我不是学生</span>
</li>
</ul>
</template>
</list2Son>
list: [
{
name: "tate",
age: 26,
single: true,
stu: false
},
{
name: "kevin",
age: 23,
single: true,
stu: true
},
{
name: "harden",
age: 28,
single: false,
stu: false
},
{
name: "Jimmy",
age: 29,
single: false,
stu: true
}
]
子组件:
<template>
<div class="wrapper">
<!-- 我是组件2的儿子 -->
<!-- <div>{{msg}}</div> -->
<slot :text="msg"></slot>
<header>
<slot name="header" say="seeyou">我是插槽头</slot>
</header>
<main>
<slot>我是插槽身</slot>
</main>
<footer>
<slot name="footer">我是插槽脚</slot>
</footer>
</div>
</template>
<script>
export default {
components:{},
props:["msg"],
data(){
return {
father:"我是list2_son子组件返回给list2父组件的值",
arr:[
{name:'vue.js'},
{name:'html权威'},
{name:'css3'},
]
}
},
watch:{},
computed:{},
methods:{},
created(){
this.$emit("father",this.father)
},
mounted(){}
}
</script>
<style scoped>
.wrapper{
color: cadetblue
}
</style>
渲染的结果就是
tate 26 我是单身我不是学生 kevin 23 我是单身我是学生 harden 28 我不是单身我不是学生 Jimmy 29 我是学生我不是单身 这里可能是一个页面标题 这里有一些联系信息 我是list2_son子组件返回给list2父组件的值
普通插槽解释:普通插槽在意的是你摆放在子组件的上下文位置
总结:作用域插槽的实用场景为父组件内调用不同显示形式的模板,就可以通过这种传参给子组件,然后子组件把参数返回给父组件在父组件页面操控子组件显示形式

浙公网安备 33010602011771号