vue2中如何使用函数式组件

函数式组件(functional component)是一个不持有状态 data 、实例 this 和生命周期的组件。

函数式组件没有 data、生命周期和 this ,函数式组件又叫无状态组件(stateless component)。

模板定义:template functional

<template functional>
  <div>
    <h1>{
  { props.title }}</h1>
  </div>
</template>

<script>
  export default {
     
    name: 'FunOne',
    props: {
     
      title: [String]
    }
  }
</script>

<style></style>

render 函数定义 – functional: true

export default {
   
  name: 'FunTwo',
  functional: true,
  props: {
   
    title: [String]
  },
  render(h, {
    
    props
  }) {
   
    return h('div', {
   }, [h('h1', {
   }, props.title)])
  }
}

不能这样定义:

<template>
  <div>
    <h1>{
  { title }}</h1>
  </div>
</template>

<script>
  export default {
     
    name: 'FunOne',
    // NOTE 不能这样定义
    functional: true,
    props: {
     
      title: [String]
    }
  }
</script>

<style></style>

定义一个函数式组件 MyInput,看看如何使用 props、data 以及事件

MyInput.jsx

export default {
   
  name: 'MyInput',
  // 声明是一个函数式组件
  functional: true,
  props: {
   
    value: {
   
      type: [String, Number],
      default: ''
    }
  },
  // NOTE 函数式组件没有 this
  render(h, context) {
   
    const {
   
      props,
      listeners,
      data
    } = context
    return h('input', {
   
      // DOM 属性
      domProps: {
   
        value: props.value
      },
      on: {
   
        input: ({
    
          target
        }) => {
   
          data.on['my-change'](Math.random().toString(36))
          // listeners 是 data.on 的别名
          listeners['my-input'](target.value)
          listeners.input(target.value)
        }
      }
    })
  }
}

在 render 函数中使用 MyInput

import MyInput from './MyInput'
export default {
   
  name: 'MyInputExample',
  
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值