插槽的三种写法---可传值

## 插槽

1. 说明:Vue 实现了一套内容分发的 API,定义时不知道具体要显示什么,只是留出来显示的位置,在组件调用时写具体内容,能展现在预留的位置上。

2. 定义:使用  标签预留位置

3. 调用组件时,写具体的要呈现的内容,要显示在标签中

   1. 匿名插槽

<slot></slot>
<slot name='default'></slot> //相当于有默认名字

    2. 具名插槽

// 定义语法: 
<slot name='xx'></slot> 
// 使用:   
<template v-slot:xx> 内容 </template>

    3. 作用域

 // 说明:传递数据 
 // 插槽数据 传递给外部使用
  <slot name="footer" :msg='msg' title='静态数据'></slot>
 // 接受数据对象:
  <template v-slot:xx='data'> 内容 </template> 
  
  data={msg:'',title:''}

    4. 简写方式

v-slot:xxx=''  简写 #xxx=''

    5. 后备数据 默认值

    6. 动态插槽名

            <template v-slot:[ft]="data">
                <h3>我是底部:{{ data.msg }}</h3>
            </template>

  附录:

(1)匿名插槽

<template>
  <!-- 此为父组件 -->
  <div>
    <p>父亲</p>
    <Child>
      <span>自定义内容</span>
    </Child>
  </div>
</template>

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

<style>
</style>
<template>
  <!-- 此为子组件 -->
  <div>
      
    <p>儿子</p>
    <!-- 匿名插槽 -->
    <slot></slot>

  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
};
</script>

<style>
</style>

 运行结果:

 

(2)具名插槽

<template>
  <!-- 此为子组件 -->
  <div>
      
    <p>儿子</p>
    <!-- 具名插槽 -->
    <slot name="header">默认值</slot>

  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
};
</script>

<style>
</style>
<template>
  <!-- 此为父组件 -->
  <div>
    <p>父亲</p>
    <Child>
      <!-- 子组件具名插槽名称header -->
      <template #header>
        <!-- v-slot属性(或者#)只能在<template>上面使用 -->
        <h1>我不是默认值</h1>
      </template>
    </Child>
  </div>
</template>

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

<style>
</style>

 运行结果:

 

(3)作用域插槽

<template>
  <!-- 此为子组件 -->
  <div>
      
    <p>儿子</p>
    <!-- 作用域插槽 -->
    <slot name="header" :data="msg">默认值</slot>

  </div>
</template>

<script>
export default {
  data() {
    return {
      msg:"子组件的信息"
    };
  },
};
</script>

<style>
</style>
<template>
  <!-- 此为父组件 -->
  <div>
    <p>父亲</p>
    <Child>
      <!-- 子组件具名插槽名称header 自定义对象名 -->
      <template #header="info">
        <h1>
          我接受{{info.data}}
        </h1>
      </template>
    </Child>
  </div>
</template>

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

<style>
</style>

 运行结果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值