vue中的插槽的使用

1.单个插槽 | 默认插槽 | 匿名插槽

匿名插槽就是可以在父组件中的子组件的标签中直接添加内容

子组件A:

<template>
  <div class="dialog">
 		<div>我是A组件中的对话框<div>
 		<slot></slot>
	</div>
</template>

<script>
	export default {
  	name: "diolage",
  	props: {
    	options: {
        type:String
      }
  	}
	}

      
</script>


父组件:(在组件外, 我们可以往插槽里填入任何元素, dialog-a为组件的名称)

<template>
	<dialogPage :options="hello"> // 只有子组件中使用了slot才能成功在此标签中添加内容
   		<button>按钮</button>
   		// ... 可以是任何元素
	</dialogPage>
</template>

<script>
  import dialogPage from './dialog'
	export default {
  	name: "Home",
    components:{
    		dialogPage
    },
  	data() {
    	return {
      	hello:'我是父组件的值'
      }
  	}
	}
</script>

2.具名插槽

具名插槽就是一个拥有name属性的插槽,具名插槽可以在同一组件中多次使用。


子组件A:

<template>
  <div class="dialog">
 		<div>我是A组件中的对话框<div>
 		<slot name="slotUp"></slot> // 具名插槽
		<slot name="slotDown"></slot> // 具名插槽
		<slot></slot> //匿名插槽
	</div>
</template>

<script>
	export default {
  	name: "diolage",
  	props: {
    	options: {
        type:String
      }
  	}
	}

      
</script>


父组件:(在组件外, 我们可以往插槽里填入任何元素, dialog-a为组件的名称)
没有slot属性的html模板默认关联匿名插槽。

<template>
	<dialogPage :options="hello"> 
 		<template slot="slotUp">
   		<button>按钮</button>
 		</template>
		<template slot="slotDown">
   		<a>按钮</a>
 	  </template>
		<template>  
   		<a>按钮</a>
 	  </template>		
	</dialogPage>
</template>

<script>
  import dialogPage from './dialog'
	export default {
  	name: "Home",
    components:{
    		dialogPage
    },
  	data() {
    	return {
      	hello:'我是父组件的值'
      }
  	}
	}
</script>

3.作用域插槽 | 带数据的插槽

作用域插槽就是一个可以携带数据的具名插槽,称为作用域插槽。

子组件A:

<template>
  <div class="dialog">
 		<div>我是A组件中的对话框<div>
    <slot name="slotData" :message="message"></slot> // 作用域插槽
 		<slot name="slotUp"></slot> // 具名插槽
		<slot name="slotDown"></slot> // 具名插槽
		<slot></slot> //匿名插槽
	</div>
</template>

<script>
	export default {
  	name: "diolage",
  	props: {
    	options: {
        type:String
      }
  	},
    data(){
    	return {
      	message:'我是作用域插槽的数据'
      }  
    }
	}
</script>


父组件:(在组件外, 我们可以往插槽里填入任何元素, dialog-a为组件的名称)
没有slot属性的html模板默认关联匿名插槽。

<template>
	<dialogPage :options="hello"> 
    <template slot="slotData" slot-scope="scope"> // 作用域插槽
    	<button>{{scope.message}}</button>
  	</template>
	</dialogPage>
</template>

<script>
  import dialogPage from './dialog'
	export default {
  	name: "Home",
    components:{
    		dialogPage
    },
  	data() {
    	return {
      	hello:'我是父组件的值'
      }
  	}
	}
</script>

posted @ 2021-01-15 23:56  Leader755  阅读(565)  评论(0编辑  收藏  举报