插槽指令

插槽指令

插槽

Vue实现了一套内容分发的API,将元素作为承载分发内容的出口。插槽内可以包含任何模板代码,包含HTML。插槽就是子组件提供的可替换模板,父组件可以根据需求改变模板的内容。

具名插槽比较简单,通过阅读官网就可以得到很好的理解,不过作用域插槽可能会有理解上的困难,我这里分别写了具名插槽和作用域插槽的demo,有助于大家的理解。

具名插槽与无名插槽

DEMO

my.vue 父组件

<template>
	<view>
		 <child>
			 <span>我是无名插槽</span>
			 <span>我是无名插槽</span>
			 <span>我是无名插槽</span>
			 <block slot='footer'>
				 我是有名插槽footer
			 </block>
			 <block slot='head'>
				 我是有名插槽head
			 </block>
		 </child>
	</view>
</template>

<script>
	import child from './chacaotest.vue'
	export default {
		components:{
			child
		},
		data() {
			return {
				
			}
		},
		methods: {
			
		}
	}
</script>

<style>

</style>

chacaotest.vue

<template>
	<view>
		<div>
		        这里是slot-child组件
		        <br>
		        <slot>原本的无名插槽</slot>
		        <br>
		        <slot name="head">原本的head</slot>
		        <br>
		        <slot name="footer">原本的footer</slot>
		        <slot name="footer">原本的footer</slot>
		        <slot name="footer">原本的footer</slot>
				<br>
				<slot name="func">原本的func</slot>
				
		 </div>
		 
	</view>
</template>

<script>
	
	export default {
		
		data() {
			return {
				
			}
		},
		methods: {
			
		}
	}
</script>

<style>

</style>

效果

image-20200331180429898

简单实用总结

1 如果没有指名道姓传入插槽,会分配给无名插槽,无名插槽里面原有的内容会被替换掉。

2 指名道姓传入有名插槽,有名插槽默认的内容会被替换掉。

3 无名插槽和有名插槽互相不影响。

作用域插槽

作用域插槽提供了一种新玩法,“插槽prop”(demo中会更直观的介绍),通过“插槽prop”,父组件可以接收到子组件的数据,并且可以对数据进行操作,展现成父组件想要实现的样子。

插槽 prop允许我们将插槽转换为可复用的模板,这些模板可以基于输入的 prop 渲染出不同的内容。这在设计封装数据逻辑同时允许父级组件自定义部分布局的可复用组件时是最有用的

DEMO

app.vue

</template>
<script>
import slotChild from '@components/slot-child.vue'
export default {
    name: 'app',
    data () {
        return {
            slotList: [
                {
                  title: '围城',
                  name: '钱钟书'
                },
                 {
                  title: '追风筝的人',
                  name: '卡勒德·胡赛尼'
                },
                 {
                  title: '灿烂千阳',
                  name: '卡勒德·胡赛尼'
                }
            ]
        }
    }
</script>
}

slot-child.vue

<template>
    <div>
        <ul>
            <slot name="slot-scope" v-for="item in slotList" v-bind="item">
                <li>书名:《{{item.title}}》; 作者:{{item.name}}</li>
            </slot>
        </ul>
    </div>
</template>
<script>
export default {
    name: 'slotChild',
    props:{
        slotList: {
          type: Array,
          default: () => []
        }
    },
    data () {
        return {}
    }
}
</script>

最终效果

image-20200331173941630

posted @ 2020-03-31 18:14  张明岩  阅读(188)  评论(0编辑  收藏  举报