vue 插槽

vue的slot主要分三种,默认插槽,具名插槽,作用域插槽;使用插槽是在存在父子关系的组件中使用,我们可以在子组件中决定插槽的位置,同时子组件也可以给这些插槽的默认信息,当父组件中没有需要给子组件插槽插入信息时,显示的是子组件插槽定义的默认信息。

1 默认插槽:<slot></slot>

子组件

在子组件中定义一个默认插槽:

<template>
  <div class="container">
    <span>我是子组件</span>
    <slot>子组件的默认信息</slot>
  </div>
</template>

<script>
export default {
  components: {
  },
  computed: {
  },
  data() {
    return {
      
    };
  },
父组件使用

<template>
  <div class="app-container calendar-list-container">
    <select-org></select-org>
  </div>
</template>

<script>
export default {
  components: {
    selectOrg: () => import("@common/components/selectOrg"),
  },
}

在父组件中添加一个p标签

<template>
  <div class="app-container calendar-list-container">
    <select-org>
        <p>我是父组件</p>
    </select-org>
  </div>
</template>

<script>
export default {
  components: {
    selectOrg: () => import("@common/components/selectOrg"),
  },
}

此时的页面

如果子组件没有使用插槽,页面中是不会展示父组件中的p标签的。

父组件定义要插入到子组件的插槽的内容,并不一定只有是dom结构类型的,也可以是一个组件,也可以是普通的数据结构,只要子组件有定义插槽,就会把内容填充进去。

 

2 具名插槽:子组件<slot name="名称"></slot>   父组件 <template v-slot:header></template>

子组件

<template>
  <div class="container">
    <slot name="header"></slot>
    <span>我是子组件</span>
    <slot name="footer"></slot>
  </div>
</template>
父组件

<template>
  <div class="app-container calendar-list-container">
    <select-org>
        <template v-slot:header>
            <p>header</p>
        </template>
        <template v-slot:footer>
            <p>footer</p>
        </template>
    </select-org>
  </div>
</template>

页面展示

子组件可以定义多个同名的具名插槽。

3 作用域插槽

插槽可以访问子组件中的数据

父组件

<template>
  <div class="app-container calendar-list-container">
    <select-org>
        <template v-slot:default="user">   
            <div class="tmp">
                <span v-for="item in user.data" :key="item">{{item.name}}</span>
            </div>
        </template>
    </select-org>
  </div>
</template>
子组件

<template>
  <div class="container">
    <span>我是子组件</span>
    <slot :data="data"></slot>  
  </div>
</template>

<script>
export default {
  data() {
    return {
      data:[
        {name:'a'},
        {name:'b'}
      ]
    };
  },

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值