Vue中的插槽---slot

一:什么是插槽?

  • 插槽(Slot)是Vue提出来的一个概念,正如名字一样,插槽用于决定将所携带的内容,插入到指定的某个位置,从而使模板分块,具有模块化的特质和更大的重用性。
  • 插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制

二:怎么用插槽?

2.1默认插槽

  子组件

<template>
    <div class="slotcontent">
        <ul>
            <!--<slot></slot>-->
            <li v-for="item in items">{{item.text}}</li>
        </ul>
    </div>
</template>
 
<script>
    export default{
        data(){
            return{
                items:[
                    {id:1,text:'第1段'},
                    {id:2,text:'第2段'},
                    {id:3,text:'第3段'},
                ]
            }
        }
    }
     
</script>
 
<style scoped>
     
</style>

 父组件

<template>
    <div>
        <h2>首页</h2>
        <router-link to="/home/details">跳转到详情</router-link>
        <p>父组件</p>
        <slotshow>
            <p>{{msg}}</p>
        </slotshow>
    </div>
</template>
 
<script>
    import slotshow from '../components/slotshow'
    export default{ data(){ return{ msg:"测试内容" } }, components:{ slotshow } } </script> <style> </style>

效果图:

解释:这种情况是如果要父组件在子组件中插入内容 ,必须要在子组件中声明slot 标签  ,如果子组件模板不包含<slot>插口,父组件的内容<p>{{msg}}</p>将会被丢弃。

 当slot存在默认值<slot><p>默认值</p></slot>,且父元素在<slotshow></slotshow>中没有要插入的内容时,会显示<p>默认值</p>(p标签会去掉),当slot存在默认值,且父元素在<child>中存在要插入的内容时,则显示父组件中设置的值,

2.2 具名插槽

子组件

<template>
  <div class="slottwo">
    <div>slottwo</div>
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>

解释:在子组件中定义了三个slot标签,其中有两个分别添加了name属性header和footer

父组件

<template>
  <div>
    我是父组件
    <slot-two>
      <p>啦啦啦,啦啦啦,我是卖报的小行家</p>
      <template slot="header">
          <p>我是name为header的slot</p>
      </template>
      <p slot="footer">我是name为footer的slot</p>
    </slot-two>
  </div>
</template>

解释:在父组件中使用template并写入对应的slot值来指定该内容在子组件中现实的位置(当然也不用必须写到template),没有对应值的其他内容会被放到子组件中没有添加name属性的slot中。

2.3 作用域插槽

 子组件

<template>
  <div>
    我是作用域插槽的子组件
    <slot :data="user"></slot>
  </div>
</template>

<script>
export default {
  name: 'slotthree',
  data () {
    return {
      user: [
        {name: 'Jack', sex: 'boy'},
        {name: 'Jone', sex: 'girl'},
        {name: 'Tom', sex: 'boy'}
      ]
    }
  }
}
</script>

解释:在子组件的slot标签上绑定需要的值

父组件

<template>
  <div>
    我是作用域插槽
    <slot-three>
      <template slot-scope="user">
        <div v-for="item in user.data" :key="item.id">
        {{item}}
        </div>
      </template>
    </slot-three>
  </div>
</template>

解释:在父组件上使用slot-scope属性,user.data就是子组件传过来的值

大概是可以这么理解的:

我理解的就像是函数的参数变量一样
function(filed){
......
field
......
}
这个slot就是这个变量,随便我们插入到哪个位置(自己预定义)

参考文档:

https://www.cnblogs.com/loveyt/p/9946450.html

https://www.cnblogs.com/qq735675958/p/8377761.html

猜你喜欢

转载自www.cnblogs.com/DZzzz/p/11881880.html