vue.js-使用slot插槽分发内容

最初在 <slot> 标签中的任何内容都被视为备用内容。备用内容在子组件的作用域内编译,并且只有在宿主元素为空,且没有要插入的内容时才显示备用内容。

一、单个插槽

子组件,备用内容在子组件的作用域内编译,并且只有在宿主元素为空时,且没有要插入的内容时才显示备用内容

1.parent.vue

<div id="exp1">
	<h1>我是父组件的标题</h1>
    <v-child>
		<p>使用slot</p>
	</v-child>
</div>
<script>
import child from '@/components/child/child'
export default {
	components: {
		'v-child':child
	}
}
</script>

2.child.vue

<div id="child">
	<h2>我是子组件的标题</h2>
	<slot></slot>
</div>
<script>
export default {
}
</script>

二、具名插槽:

父:slot="header"   子:<slot name="header"></slot>

1.parent.vue

<div id="exp1">
	<h1>我是父组件的标题</h1>
    <v-child>
		<h1 slot="header">这是一个页面的标题</h1>
		<p>主要内容的一个段落</p>
		<p>主要内容的另外一个段落</p>
		<p slot="footer">这是一些页脚信息</p>
	</v-child>
</div>
<script>
import child from '@/components/child/child'
export default {
	components: {
		'v-child':child
	}
}
</script>

2.child.vue

<div id="child">
	<h2>我是子组件的标题</h2>
	<slot name="header"></slot>
	<slot></slot>
	<slot name="footer"></slot>
</div>
<script>
export default {
}
</script>


三、作用域插槽:

 在父组件的模板里,使用一个Vue自带的特殊组件<template> ,并在该组件上使用scope属性,值是一个临时的变量,存着的是由子组件传过来的prop对象,在下面的例子中我把他命名为props。获得由子传过来的prop对象。这时候,父组件就可以访问子组件在自定义属性上暴露的数据了。

1.parent.vue

<div id="exp1">
	<h1>我是父组件的标题</h1>
    <v-child>
		<template scope="props" slot="child-ul">
			<li class="child-ul">{{ props.text }}</li>
		</template>
	</v-child>
</div>
<script>
import child from '@/components/child/child'
export default {
	components: {
		'v-child':child
	}
}
</script>

2.child.vue

<div id="child">
	<h2>我是子组件的标题</h2>
	<ul>
		<slot name="child-ul" v-for="item in animal" v-bind:text="item.name"></slot>
	</ul>
</div>
<script>
export default {
	data () {
		return {
			 animal:[
                    {name:'大象'},
                    {name:'小狗'},
                    {name:'小猫'},
                    {name:'老虎'}
                ]
		}
	}
}
</script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值