Vue中的插槽介绍

1.插槽是什么

简单的说就是在组件内部留下一个或者多个的空位(插槽), 我们可以将对应的模板代码放进去。插槽的出现让组件变得更加得灵活。在诸如element-ui,iview等组件库中都充分利用了插槽的作用。

2.插槽的分类

匿名插槽:就是没有名字的插槽,也就是默认的插槽;
具名插槽:具有一个确定名字的插槽,可以通过这个名字找到这个插槽;
作用域插槽:说白了就是在组件上的属性,在组件元素内部使用,这么说可能不是很能理解,稍后再解释;

3.匿名插槽

话不多说,先上代码:

//这是一个组件,我们以单页面的形式给出
Vue.component("component-one",{
	template:`
		

Hellp

`
}) //没有用插槽引用这个组件 <component-one></component-one> //渲染结果: <div> <p>Hellp</p> </div> ===================================== //添加一个插槽的引用组件 <component-one> 你好 </component-one> //渲染结果: <div> <p>Hellp</p> 你好 </div>

这就是匿名插槽,这个位置会被我们写入的内容所完全覆盖!
注意
通常情况下我们往插槽里面插入东西都是以template标签的形式,这样显得规范些;

//如上组件component-one使用template插入插槽
<component-one>
	<template>你好</template>
</component-one>

4.具名插槽

就是给插槽取个名字,然后再对应名字去插入内容;没有名字的就是上面的匿名插槽,也称默认插槽;

//组件定义
Vue.component("component-two",{
	template:`
		

你好

`
}) //组件引用 <component-two> <template v-slot:"one"> 这是one插槽内容 </template> <template v-slot:"two"> 这是two插槽内容 </template> <div> 这是默认(匿名)插槽 </div> </component-two> //渲染结果 <div> 你好 这是one插槽内容 这是two插槽内容 这是默认(匿名)插槽 </div>

vue >=2.6.0版本,使用v-slot替代slot 和 slot-scope。

注意四点

  1. 具名插槽的内容必须使用模板包裹
  2. 不指定名字的模板插入匿名插槽中,推荐使用具名插槽,方便代码追踪且直观清楚
  3. 匿名插槽具有隐藏的名字"default"
  4. 具名插槽的v-slot:可以缩写为#

5.作用域插槽

刚刚我们说过,作用域插槽其实就是组件上的属性在组件元素内的使用;我们来解释下这个意思:
先看一个例子:

//定义组件
<div class="child-page">
        <h1>{{title}}子页面</h1>
        <slot name="header"></slot>
        <slot name="body"></slot>
        <slot name="footer"></slot>
</div>
    props: {
        title: {
            type: String
        }
    }
//使用组件
<child-page  //组件 (父)
    :title="'我是'"
  >
    <template #header>  //组件内部 (子)
      <p>{{title}}</p>   //此处是错误的
    </template>
    <template #footer>
      <p>脚部</p>
    </template>
    <template #body>
      <p>身体</p>
    </template>
  </child-page>

父组件传递的到组件内部的插槽内容是由子组件编译的,插槽作用域由子组件决定。所以如果需要动态修改插槽的内容,需要子组件传参给父组件。

如果需要使用我们需要这样做:

//定义组件
<div class="child-page">
        <h1>{{title}}子页面</h1>
        <slot name="header" :say:"title"></slot>
        <slot name="body"></slot>
        <slot name="footer"></slot>
</div>
    props: {
        title: {
            type: String
        }
    }

//使用组件
<child-page
    :title="'我是'"
  >
    <template #header v-slot:header="say">
      <p>{{say}}</p>   //{"say":我是}
    </template>
    <template #footer>
      <p>脚部</p>
    </template>
    <template #body>
      <p>身体</p>
    </template>
  </child-page>

这就是组件上的属性:title可以在组件元素内插槽使用==>作用域插槽!!

总结:
父组件传参给子组件,props接收后,插槽slot再通过绑定属性传递参数返回给父组件,不管是模板代码还是数据,控制权完全掌握在父组件手里。

2019-11-19 好久没有写一些博文了,以后坚持每天写一点东西,让自己理解的更好些,加油!
https://www.jianshu.com/p/b0234b773b68

你可能感兴趣的:(Vue)