[Vue @Component] Pass Props Between Components with Vue Slot Scope & renderless component

Components with slots can expose their data by passing it into the slot and exposing the data using slot-scope in the template. This approach allows you to pass props down from Parent components to Child components without coupling them together.

 

For example, we have two components, Settings and Layout component:

<Settings>
    <Layout></Layout>
</Seetings>

 

We want Layout get data from Settings component, we can do it with slot-scope


Seetings.vue:

复制代码
<template>
    <div>
        <slot :header=header :footer=footer></slot>    
    </div>
</template>
<script>
import {Component, Vue} from 'vue-property-decorator'

export default class Settings extends Vue {
    header = 'This is data for header'
    footer = 'This is the data form footer'
}
</script>
复制代码

 

Actually this is the same as Renderless component:

 // Renderless component
<script>
export default {
    render() {
      return this.$scopedSlot.default({header: 'xxx', footer: 'xxx'})
   }
}
</script>

 

 

Layout.vue:

复制代码
<template>
    <div class="flex flex-col h-screen">
    <slot name="header">
      <h1 class="text-red">Please add a header!</h1>
    </slot>
    <slot name="content">
      <div class="text-red flex-grow">Please add some content</div>
    </slot>
    <slot name="footer">
      <h2 class="text-orange">Please add a footer!</h2>
    </slot>
    </div>
</template>
复制代码

 

HelloWorld.vue:

复制代码
<template>
  <Settings >
    <Layout slot-scope="props">
        <header slot='header' class='p-2 bg-blue text-white'>{{props.header}}</header>
        <div slot="content" class="flex-grow p-3">Amazing content</div>
         <h2 slot="footer" class="bg-grey-light text-blue p-2 text-center">{{props.footer}}</h2>
    </Layout>
  </Settings>
</template>

<script>

import {Component, Prop, Vue} from 'vue-property-decorator'
import Layout from './Layout';
import Settings from './Settings';

@Component({
  components: {
    Layout,
    Settings
  }
})
export default class HelloWorld extends Vue {
  @Prop({
    default: 'Default message from Hello World Component'
  })
  message

  onClick() {
    this.message = 'Goodbye'
  }
}
</script>
复制代码

 

The concept is a bit similar to Angular ngTemplateOutlet

posted @   Zhentiw  阅读(558)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-07-30 [Angular] Design API for show / hide components based on Auth
2014-07-30 [Node.js]23. Level 4: Semantic versioning
2014-07-30 [Node.js]22. Level 4: Dependency
点击右上角即可分享
微信分享提示