Vue3编写h函数式小组件

函数式编程和h函数

h函数源码 createVnode

h函数的优势 跳过了模版的编译

缺点 学习成本较高

通常用来编写按钮、弹框等小组件

<template>
  <table border>
    <tr>
      <th>name</th>
      <th>age</th>
      <th>address</th>
      <th>操作</th>
    </tr>
    <tr v-for="item in list" key="item.id">
      <td>{
   
   { item.name }}</td>
      <td>{
   
   { item.age }}</td>
      <td>{
   
   { item.address }}</td>
      <td>
        <Btn type="success">编辑</Btn>
        <Btn type="error">删除</Btn>
      </td>
    </tr>
  </table>
</template>
<script setup lang="ts">
import { ref, reactive, h } from 'vue'
const list = reactive([
  { id: 1, name: 'Tom', age: 18, address: 'Shanghai' },
  { id: 2, name: 'Jerry', age: 20, address: 'Beijing' },
  { id: 3, name: 'Jim', age: 22, address: 'Shenzhen' },
  { id: 4, name: 'Jim', age: 22, address: 'Shenzhen' },
  { id: 5, name: 'Jim', age: 22, address: 'Shenzhen' }
])

// 定义按钮的状态
interface Props {
  type: 'success' | 'error'
}

// 函数式组件
const Btn = (props:Props, ctx:any) => { // 这里接收的参数和setup函数一样
  // console.log(ctx)
  // 第一个参数是创建的节点,第二个参数是节点的属性,第三个是节点的内容
  return h('button', 
    {
      style: {
        color: props.type ==='success'? 'green' :'red'
      },
      onClick: () => { 
        // ctx.emit('click', 2333) // 派发事件 并 传参
        if(props.type === 'success'){
          console.log('编辑')
        } else {
          console.log('删除')
        }
      }
    }
  , ctx.slots.default())
}

</script>
<style scoped></style>

猜你喜欢

转载自blog.csdn.net/xyphf/article/details/134393439