vue 自定义组件 + 函数式组件

自定义组件

一、思路

1、定义子组件

2、父组件中引入

3、注册

4、父组件传参,子组件通过props接收

5、父组件自定义组件标签中内容,子组件slot接收

二、示例:父组件传入数值,子组件对应渲染h1~h6标签

父组件Fa.vue

<template>
  <div id="fa">
    <Son :type="2"></Son>
  </div>
</template>

<script type='text/ecmascript-6'>
import Son from "@/components/Son.vue";
export default {
  name: "Fa",
  components: {
    Son,
  },
};
</script>
<style>
</style>

子组件Son.vue

<template>
  <div>
    <h1 v-if="type === 1">
        <slot></slot>
    </h1>
    <h2 v-if="type === 2">
        <slot></slot>
    </h2>
    <h3 v-if="type === 3">
        <slot></slot>
    </h3>
    <h4 v-if="type === 4">
        <slot></slot>
    </h4>
    <h5 v-if="type === 5">
        <slot></slot>
    </h5>
  </div>
</template>

<script>
export default {
  props: ["type"]
};
</script>

缺点:如果是要动态配置100条数据,难道要v-if进行100条条件判断吗?

解决:函数式组件

函数式组件

一、引入

函数组件参数说明:

  1. functional:true, // 约定是函数组件

  2. render

(1)是一个函数

(2)函数组件,只有render方法

(3)render中,不能写template

(4) render函数默认接收两个形参,第一个是createElement(type,attrs:obj,children),非常类似jsx写法。 第二个参数是context,可以理解成:组件实例,这就要求对vue实例属性非常了解

常见如:

context.slots().default: slot内容,  
context.props: 父子组件传递的属性

二、代码:

Fa.vue

<template>
  <div id="fa">
    <Son :type="4">8880008</Son>
  </div>
</template>

<script type='text/ecmascript-6'>
import Son from "@/components/Son.js";
export default {
  name: "Fa",
  components: {
    Son,
  },
};
</script>
<style>
</style>

Son.js(函数组件)

export default {
    functional:true,
    render(h,context){
        let t = 'h' + context.props.type;
        return <t>{context.slots().default}</t>;
    }
};
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值