1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nuxt3でトースト機能の実装

Posted at

スクリーンショット 2025-04-20 17.25.33.png

Nuxt3の自前ブログを使って、色々な機能を試して実装していきます。
最初にトースト機能を実装してみたいと思います。

↓作成したブログはこちら

動作環境

  • Nuxt: 3.16.2
  • @nuxt/ui: 3.0.2

全体構成

準備

1. NuxtUIとは

Nuxt UI は、Reka UI、Tailwind CSS、Tailwind Variants の強みを融合し、洗練された、アクセシブルで高パフォーマンスなユーザーインターフェースを構築するための、他に類を見ないツール群を開発者に提供します。

Nuxtに簡単にUIコンポーネントを組み込めるためのライブラリのことですね。

2. Nuxt UIの導入

2-1. Nuxt UIのインストール

プロジェクトのルートディレクトリで以下のコマンドを実行します。

npm install @nuxt/ui

package.jsonに次のように追加されているはずです。

package.json
{
  ...
  "dependencies": {
    ...
    "@nuxt/ui": "^3.0.2", # 追加されている
    ...

2-2. nuxt.config.tsに設定追加

そして次にnuxt.config.tsを編集します。

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxt/ui'],
});

2-3. CSSの編集

プロジェクト全体で使用しているcssファイルを指定します。

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxt/ui'],
  css: ['~/assets/css/main.css'] // 追加
})

そしてそのcssファイルでtailwindとNuxt UIのインポートをします。

main.css
@import "tailwindcss";
@import "@nuxt/ui";

2-4. app全体をApp Componentで囲う

プロジェクト全体でToastやTooltipを使用できるようにするための設定です。

app.vue
<template>
  <UApp>
    <NuxtPage />
  </UApp>
</template>

私のプロジェクトではNuxtLayoutを使用しているので、このような実装となりました。

app.vue
<template>
  <UApp>
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </UApp>
</template>

これでトースト機能を実装する準備が整いました。

実装

まずは

<script lang="ts" setup>
const toast = useToast();

function showToast() {
  const props = {
    title: 'ブログにようこそ!',
  };
  toast.add(props);
};

// ページを初期表示したときに呼び出す
onMounted(() => {
  showToast();
});
</script>

まずはuseToast関数を使用してtoastを生成します。

その次にtoastのadd関数にオブジェクトを渡します。
他にも細かい制御(アイコンやクローズボタンなど)もできるので、以下を参考にしてください。

ブログを表示する際にtoastが表示されるようになりました🎉
toast.gif

さいごに

Nuxt UI他にも多くのIconを用意していたり、ColorModeを設定できたりするようなので、少しずつ機能を足していきたいと思います。

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?