1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Nuxt】script(tsx)のみでlayoutコンポーネント的なものを作る

Last updated at Posted at 2023-02-18

こんにちは。
今回は備忘録的にNuxtで<template>を使用せずに<script lang="tsx">のみで開発をしている際に、Reactのlayoutコンポーネント的なものを作る方法を綴ります。

Vueは本来、layouts/default.vueを書くことで共通レイアウトを作ってくれるという機能がありますので、通常はそれを使用する方が良いかもしれません。

通常の場合

通常の場合、.vue<script><template><style>の構成で記述されるため、親コンポーネントから子コンポーネントに差し込みを行うslotが使用できるので以下のようなシンプルなコードになります。

子コンポーネント(Layout.vue)
<template>
    <main>
        <slot></slot>
    </main>
</template>
親コンポーネント
<template>
    <Layout>
        <!-- ここに要素が挿入できる -->
    </Layout>
</template>

<script lang="tsx">のみの場合

<script lang="tsx">のみの場合、すなわち.vue<script>のみで構成したいときは、<slot></slot>というシンプルな記述を使うことができません。しかし、少し形を変えることだけで同様のことを実現できるようです。

子コンポーネント
<script lang="tsx">
    export default defineComponent({
        setup(_, { slots }){
            return () => (
                <main>
                    {slots.default && slots.default()}
                </main>
            )
        }
    })
</script>
親コンポーネント
<script lang="tsx">
    import LayoutVue from '~/components/templates/Layout.vue';
    
    export default defineComponent({
        render(){
            return(
                <LayoutVue>
                    // ここに要素が挿入できる
                </LayoutVue>
            )
        }
    })    
</script>

さいごに

以上が<script lang="tsx">のみでlayoutコンポーネント的なものを作る方法でした。
Nuxt、Vue共に超初心者ですので、間違っていたらご指摘頂けると幸いです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?