[Vue @Component] Pass Props to Vue Functional Templates

本文介绍如何在 Vue.js 中使用功能性模板组件,通过仅使用模板标签和 props 对象来创建可配置的模板,无需编写额外的业务逻辑代码。文章展示了如何将此方法应用于布局组件,以简化代码并提高可维护性。

Functional templates allow you to create components consisting of only the template tag and exposing the props passed into the template with the props object off of the template context. This approach allows you to build simple configurable templates without having to write any backing code.

 

From the code in previous post:

<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
  }
})

 

We create two functional template component 'Header' and 'Footer':

<!-- components/Heade.vuer -->

<template functional>
      <header slot='header' class='p-2 bg-blue text-white'>{{props.header}}</header>
</template>
<!-- components/Footer.vue -->

<template functional>
    <h2 slot="footer" class="bg-grey-light text-blue p-2 text-center">{{props.footer}}</h2>
</template>

 

Functional template works pretty much like React functional component:

const header = props => <header>{{props.header}}</header>

Just in Vue, you just need to add 'functional' directive to the <template>, don't need to add any js code.

 

exports those componets in components/index.js file:

export { default as Header } from "./Header"
export { default as Footer } from "./Footer"

 

Using those component to refactor the code:

<template>
  <Settings >
    <Layout slot-scope="{header, footer}">
        <Header :header="header"></Header>
        <div slot="content" class="flex-grow p-3">Amazing content</div>
        <Footer :footer="footer"></Footer> 
    </Layout>
  </Settings>
</template>

<script>

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

import {Header, Footer} from './components';


@Component({
  components: {
    Layout,
    Settings,
    Header,
    Footer
  }
})

 

转载于:https://www.cnblogs.com/Answer1215/p/9362569.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值