◆

Vue3 h 函数与 TSX 渲染函数写法

2023-02-02 01:370

插件配置

@vitejs/plugin-vue-jsx

vite 中的 plugin 配置

import vueJsx from '@vitejs/plugin-vue-jsx';

plugin: [vueJsx()];

h 函数

返回一个”虚拟节点“,通常缩写为 VNode:一个普通对象, 其中包含向 Vue 描述它应在页面上渲染哪种节点的信息,包括所有子节点的描述。它的目的是用于手动编写的渲染函数

  • type:类型:String | Object | FunctionHTML 标签名、组件、异步组件或函数式组件。使用返回 null 的函数将渲染一个注释。此参数是必需的。

  • props:类型:Object 一个对象,与我们将在模板中使用的 attribute、prop 和事件相对应。可选。

  • children:类型:String | Array | Object 子代 VNode,使用 h() 生成,或者使用字符串来获取“文本 VNode”,或带有插槽的对象。可选。

使用示例

<script lang="tsx">
import Child from './child.vue';
import { defineComponent, h } from 'vue';

export default defineComponent({
  setup() {
    function handClick() {
      alert(1);
    }

    return () =>
      h('div', {}, [
        'Some text comes first.',
        h(
          'h1',
          {
            class: 'scrollbar__thumb',
            onClick: handClick,
            style: {
              fontSize: '30px',
              color: 'blue',
            },
          },
          'A headline',
        ),
        h(Child, {
          someProp: 'foobar',
        }),
      ]);
  },
});
</script>

<style scoped>
.scrollbar__thumb {
  background: lightblue;
}
</style>

child 代码

<script lang="tsx">
import { defineComponent, h } from 'vue';

export default defineComponent({
  setup() {
    return () => h('div', { style: { color: '#eee' } }, '这是子组件');
  },
});
</script>

<style scoped></style>

tsx 写法

示例

<script lang="tsx">
import { defineComponent } from 'vue';
import Child from './child.vue';

export default defineComponent({
  setup() {
    return () => (
      <div style="color: red" class="my-test">
        111
        <p>333</p>
        <Child />
      </div>
    );
  },
});
</script>

<style scoped>
.my-test {
  background: lightblue;
}
</style>

tsx-setup 写法

<script lang="tsx" setup>
import { render } from 'vue';

render(
  <div ref="test" id="test1" style="text-align: center">
    333
    <p style="color: red">test</p>
  </div>,
  document.body,
);
</script>

<style scoped>
.my-test {
  background: lightblue;
}
</style>
💬留言板0

还没有留言,来发表第一条吧~

PAGE LOAD / LIVEVue3 h 函数与 TSX 渲染函数写法加载中