zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    【每日更新】全栈笔记
    【SQL模板】四.插入/更新 列模板TSQL
    【SQL模板】三.插入/更新 数据模板TSQL
    【SQL模板】二.创建表视图模板TSQL
    【SQL模板】一.修改/新增存储过程TSQL
    【转】Https内部机制基础知识
    【每日更新】【SQL实用大杂烩】
    expandableListview的默认箭头箭头怎样移到右边
    ExpandableListView的首次加载全部展开,并且点击Group不收缩、
    android 制作9.png图片
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9351069.html
Copyright © 2011-2022 走看看