📑

Vue3: コンポーネントを透過するコンポーネントを作る

に公開

やりたいこと: 使う側がタグやコンポーネントを指定してプロパティを補完してくれる


buttonタグとして使えばbutton[type='']を指摘してくれる


aタグとして使えばhrefが使える


RouterLinkとして使えばtoの漏れを指摘してくれる

結論: tsxを使う

@vitejs/plugin-vue-jsxが必要です。
使う側は<script setup lang="ts">で使用できます。

MyButton.tsx
import type { IntrinsicElementAttributes, VNode } from 'vue';
import type { RouterLink, RouterLinkProps } from 'vue-router';

// IntrinsicElementAttributes はHTMLタグの属性Attributesがまとまったオブジェクト
type Tag = keyof IntrinsicElementAttributes | typeof RouterLink;

// generics T のtypeに応じてPropsが切り替わる=>これで補完される
type Props<T extends Tag> = T extends keyof IntrinsicElementAttributes
  ? IntrinsicElementAttributes[T]
  : RouterLinkProps;

// tagを指定しない場合'button'で補完される
export default function MyButton<T extends Tag = 'button'>(
  props: {
    tag?: T;
  } & Props<T>,c
  { slots }: { slots: { default?: () => VNode[] } },
) {
  // 実際の挙動としてもデフォルトを'button'にするのを忘れてはいけません
  const { tag: Tag = 'button', ...rest } = props;

  return <Tag {...rest}>{slots.default?.()}</Tag>;
}

やりたかったのは「スタイルの共有」

ボタンの見た目だけど、aタグやRouterLinkを使いたい場面はままあると思います。スタイルを共有するだけならやり方はいくつかあります。

class や @apply(TailwindCSS)を使う

私は主にTailwindCSSを使っています。
悪い方法ではないと思いますが、スタイルの共有をするためだけに、今まで使わずにいたclass や @applyを使うのに抵抗がありました。

aタグやRouterLinkでButtonコンポーネントを囲う

よろしくありません。この方法だと、タブでフォーカスを移動したときに、aタグ=>buttonタグと移動します。タブの移動を抑制するために、buttonタグにtabindex="-1"を忘れずに書かないといけません。

イメージ
私は何も知らずに何も考えずにこの方法を長年使ってきて痛い目にあいました。

VueのSFCではできなかった

.vueファイルでも、こんな感じで全く同じことができそうです。

MyButton.vue
<script lang="ts">
import type { IntrinsicElementAttributes } from 'vue';
import type { RouterLink, RouterLinkProps } from 'vue-router';

type Tag = keyof IntrinsicElementAttributes | typeof RouterLink;

type Props<T extends Tag> = T extends keyof IntrinsicElementAttributes
  ? IntrinsicElementAttributes[T]
  : RouterLinkProps;
</script>

<script setup lang="ts">
const { tag = 'button' } = defineProps<
  {
    tag?: Tag;
  } & Props<Tag>
>();
</script>

<template>
  <component :is="tag" v-bind="$attrs">
    <slot></slot>
  </component>
</template>

でも、実際にはできません。type Props<T extends Tag>のところで、[@vue/compiler-sfc] Unresolvable type: TSConditionalTypeが発生してしまうからです。

TSConditionalTypeでコンパイルエラーになって困るという記事は23年くらいから見つかっています。おそらくこのまま対応されないのだと思います。
参考:https://github.com/vitejs/vite-plugin-vue/issues/167#issuecomment-1537641637

要するに、vueではTSConditionalTypeが使えず、tsxではTSConditionalTypeが問題にならないため、tsxを使えばコンポーネントを透過するコンポーネントが作れる、ということです。

応用編: すべてのコンポーネントに対応

使うかは置いといて、こうすればすべてのコンポーネントに対応できる!
※ComponentPropsはvue-component-type-helpersから

MyButton.tsx
import type { Component, IntrinsicElementAttributes, VNode } from 'vue';
import type { ComponentProps } from 'vue-component-type-helpers';

type Tag = keyof IntrinsicElementAttributes | Component;

type Props<T extends Tag> = T extends keyof IntrinsicElementAttributes
  ? IntrinsicElementAttributes[T]
  : ComponentProps<T>;

Discussion