vue3-h函数式组件

75 阅读1分钟

h函数

  • 基本和tsx函数式写法一致
<template>
  <div>
    <div>我是index</div>
    <div class="box">
      <table border="2">
        <tr>
          <th>name</th>
          <th>age</th>
          <th>op</th>
        </tr>
        <tr v-for="item in list" :key="item.name">
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>
            <span style="margin-right: 10px"><btn type="success" />编辑</span>
            <span><btn type="error" />删除</span>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'ApplyAWSIndex',
};
</script>
<script setup lang="ts">
import { ref, h } from 'vue';
import { Button } from 'tdesign-vue-next';

const list = ref([
  { name: 'menffy', age: 19 },
  { name: 'menffy', age: 19 },
  { name: 'menffy', age: 19 },
  { name: 'menffy', age: 19 },
  { name: 'menffy', age: 19 },
  { name: 'menffy', age: 19 },
]);
interface Props {
  type: 'success' | 'error';
}
// 第一个参数:创建的节点
// 第二个参数:节点属性
// 第三个参数:节点的内容
const Btn = (props: Props, ctx) => {
  console.log('ctx', ctx);
  return h(
    'button', // 直接传入组件对象也可以,比如tdesign的Button
    {
      id: 'test',
      class: 'testClass',
      style: { color: props.type === 'success' ? 'green' : 'red' },
      onClick: () => {
        ctx.emit('click', 123);
        console.log('click');
      },
    },
    'click',
  );
};
</script>

<style scoped lang="less">
.box {
  background-color: white;
}
</style>

image.png

支持其他写法

image.png