Vue2插槽

作用

让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件===>子组件。

分类

默认插槽、具名插槽、作用域插槽

使用方式:

默认插槽

父组件

 <Catogary title="苹果"><img src="./assets/logo.png" /></Catogary> 
 <Catogary title="香蕉">   
   	<ul>
   		<li>123</li>
   		<li>456</li>
   		<li>789</li>   
   	</ul> 
 </Catogary>

子组件

<template>   
<div>
    <div>{{ title }}</div>
    <slot>插槽默认内容</slot>   
</div> 
</template> 

<script> 
	export default {
		name: "Catogary",  
		props: ["title"], 
 	}
 </script>
具名插槽

父组件

<Catogary>
	<img slot="pic" src="./assets/logo.png" />  
 	<template v-slot:name><template slot="name">
   		<ul>
     		<li>这是一个li</li>
     		<li>这是一个li</li>
     		<li>这是一个li</li>
   		</ul>   
 	</template> 
</Catogary>

子组件

<template>   
		<div>
 			<div>{{ title }}</div>
 			<slot name="pic">这是图片具名插槽</slot>
			<slot name="name">这是名称具名插槽</slot>   
 		</div> 
</template>

作用域插槽
  1. 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。
  2. 具体编码

App.vue

<template>   
<div id="app">
    <Catogary>
      <template scope="{dataList}">
        <ul><li v-for="item in dataList" :key="item.id">{{ item.name }}</li></ul>
      </template>
    </Catogary>
    <Catogary>
      <template scope="{dataList}">
        <ol><li v-for="item in dataList" :key="item.id">{{ item.name }}</li></ol>
      </template>
    </Catogary>  
 </div> 
 </template>

Catogary.vue

<template>   
	<div><slot :dataList="dataList"></slot></div> 
</template> 
<script> 
export default {   
	name: "Catogary",   
	data() {
   		return {
     		dataList: [
       			{ id: "001", name: "标题一" },
       			{ id: "002", name: "标题二" },
       			{ id: "003", name: "标题三" },
       			{ id: "004", name: "标题四" },
     		],
  		 };   
  }, 
  }; 
  </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值