#精品
slot 怎么传值给子组件

2024-09-20 437

在 Vue.js 中,使用具名插槽 <slot name="slotName"></slot> 可以让父组件向子组件传递特定的内容。要将值传递给子组件的具名插槽,可以使用 v-slot 指令。以下是具体的步骤和示例:

1. 在子组件中定义具名插槽

首先,在子组件中定义具名插槽:

<template>  
  <div>  
    <h2>子组件内容</h2>  
    <slot name="slotName"></slot> <!-- 具名插槽 -->  
  </div>  
</template>  

<script>  
export default {  
  name: 'ChildComponent'  
}  
</script>

2. 在父组件中使用具名插槽

在父组件中使用子组件,并通过 v-slot 指令传递内容到具名插槽:

<template>  
  <div>  
    <ChildComponent>  
      <template v-slot:slotName>  
        <p>这是传递给具名插槽的内容。</p>  
      </template>  
    </ChildComponent>  
  </div>  
</template>  

<script>  
import ChildComponent from './ChildComponent.vue';  

export default {  
  components: {  
    ChildComponent  
  }  
}  
</script>

3. 传递数据到具名插槽

如果需要从父组件向子组件传递数据,可以使用 props。以下是一个示例:

修改子组件以接收 props

<template>  
  <div>  
    <h2>子组件内容</h2>  
    <slot name="slotName" :message="message"></slot> <!-- 具名插槽,传递数据 -->  
  </div>  
</template>  

<script>  
export default {  
  name: 'ChildComponent',  
  props: {  
    message: {  
      type: String,  
      default: '默认消息'  
    }  
  }  
}  
</script>

在父组件中使用具名插槽并接收数据

<template>  
  <div>  
    <ChildComponent :message="parentMessage">  
      <template v-slot:slotName="{ message }">  
        <p>这是传递给具名插槽的内容:{{ message }}</p>  
      </template>  
    </ChildComponent>  
  </div>  
</template>  

<script>  
import ChildComponent from './ChildComponent.vue';  

export default {  
  components: {  
    ChildComponent  
  },  
  data() {  
    return {  
      parentMessage: '来自父组件的消息'  
    };  
  }  
}  
</script>

总结

  • 在子组件中使用 <slot name="slotName"></slot> 定义具名插槽。
  • 在父组件中使用 <template v-slot:slotName> 传递内容。
  • 可以通过 props 将数据传递给具名插槽,并在父组件中接收这些数据。
收藏 打赏

感谢您的支持,我会继续努力的!

打开微信扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

版权声明 1 零玖吧
2 https://www.09b.cn
3 QQ68857537
4
5 访
6
7

要想程序运行完整,离不开BUG的辅助

常见问题
  • 本站所有资源仅供学习交流使用请勿商业运营,严禁使用零玖吧上的资源从事违法,侵权等任何非法活动!
查看详情
  • 是的,开通之后所有资源都可以下载!
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

本次数据库查询:121次 页面加载耗时0.827 秒