vue之slot用法

slot元素作为组件模板之中的内容分发插槽。这个元素自身将被替换。
有 name 特性的 slot 称为具名 slot。 有 slot 特性的内容将分发到名字相匹配的具名 slot。

一、单个组件

如果子组件的模板不包含 slot,那么父组件的内容就会被抛弃
父组件内容
<template>
  <div>
    <child>若子组件没有slot,则这句话不会显示</child>
  </div>
</template>

<script>
import Child from './Child.vue'
export default {
  name: 'HelloWorld',
  components:{
  	'child':Child
  }
}
</script>

子组件内容

<template>
	<div>
		<h1>我是子组件</h1>
	</div>
</template> 

浏览器显示

因为子组件没有<slot> 元素,所以父组件的内容被抛弃,现在我们在子组件加上<slot> 元素

<template>
	<div>
		<h1>我是子组件</h1>
		<slot></slot>
	</div>
</template>

此时浏览器显示

此时,父组件的内容就显示在了子组件的内容里了。

二、具名slot

上面案例中讲解的是当组件的模板中有一个slot的方法,那么一个组件中如果想使用多个slot那么此时就应该使用具名slot。

父组件内容

<template>
   <child>
     <h1 slot="h1">标题一</h1>
     <h2 slot="h2">标题二</h2>
     <h3>标题三</h3>	
   </child>
</template>

<script>
import Child from './Child.vue'
export default {
  components:{
  	'child':Child
  }
}
</script>

子组件内容

<template>
	<div>
		<h1>我是子组件</h1>
		<slot name="h1"></slot>
		<slot name="hh"></slot>
		<slot></slot>
	</div>
</template>

浏览器显示

分析:子组件中的slot有name属性,与父组件的slot的值相对应,那么就会匹配到,若子组件中slot有name属性,但父组件没有与之相对的slot的值,则会被抛弃掉。父组件没有slot值的内容则会显示在默认的slot中。如果子组件中没有默认的slot,父组件没有slot值的内容就会被抛弃。 

  

  

  

猜你喜欢

转载自www.cnblogs.com/clicklin/p/9389892.html