Vue 插槽 slot 的使用

写一个关于插槽slot的文章记录一下

首先理解 编译作用域:父级模板的所有内容都是在父级作用域里边编辑的,子模板里的所有内容都是在子作用域里面编译的.

什么是插槽?

插槽就是子组件中用<slot></slot>给一个占位符,父组件在使用子组件的时候可以在这个占位符中填充任何代码

为什么使用插槽

加强组件的复用性,降低组件的耦合性,封装公共组件的时候预留插槽,使用者在使用的时候可以根据自己的需求,决定插槽内的内容.

插槽分为默认插槽,具名插槽,作用域插槽

默认插槽

默认插槽,默认把代码全部填充进去

子组件

<template>
    <div>
       <h5>你的名字是</h5>
        <slot></slot>
    </div>
</template>
<script>
export default {
    name:'child',
    data () {
    return 
}
}
</script>

父组件

<template>
    <div>使用插槽:</div>
    <div>
      <child>
    <span>卡尔</span>
       </child>
    </div>
</template>
<script>
import child form './child'
export default {
    name:'father',
    components:{child},
    data () {
    return 
}
}
</script>

具名插槽

就是给插槽一个name属性,父组件在使用的时候使用插槽的name属性

子组件

<template>
    <div>
       <h5>我是标题</h5>
        <slot name='title'></slot>
    </div>
     <div>
       <h5>我是中间</h5>
        <slot name='main'></slot>
    </div>
    <div>
       <h5>我是底部</h5>
        <slot name='footer'></slot>
    </div>
</template>
<script>
export default {
    name:'child',
    data () {
    return 
}
}
</script>

父组件

<template>
    <div>使用插槽:</div>
    <div>
      <child>
        <template slot="title">
            <span>使用slot</span>
        </template>
        <template slot="mian">
            <span>我是中间的具体内容</span>
        </template>
        <template slot="footer">
            <span>我是底部的具体内容</span>
        </template>    
       </child>
    </div>
</template>
<script>
import child form './child'
export default {
    name:'father',
    components:{child},
    data () {
    return 
}
}
</script>

作用域插槽

父组件使用slot-scope属性来结构子组件,操作子组件的值

子组件

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

<script>
export default {
  name: 'child',
  data () {
    return {
      user: [
        {name: '王大锤'},
        {name: '铁锤'},
        {name: '翠花'}
      ]
    }
  }
}
</script>

父组件

<template>
    <div>使用插槽:</div>
    <div>
      <child>
          <template slot-scope="user">
        <div v-for="(item, index) in user.data" :key="index">
        {{item}}
       </child>
    </div>
</template>
<script>
import child form './child'
export default {
    name:'father',
    components:{child},
    data () {
    return 
}
}
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值