0
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 3 years have passed since last update.

【Nuxt.js】ボタンコンポーネントの作成について

Posted at

はじめに

こんにちは。
こちらの記事では、Nuxt.jsでボタンコンポーネントの作成方法を記しています。
誤っている点がございましたらコメントいただけると幸いです。

実装手順

ボタンの文章、遷移先リンク、色を指定できるように実装します。
(スタイルはTailwindcssで指定しています)

1. ボタンコンポーネントの作成

componentsディレクトリに、ボタンコンポーネントのファイルを作成して、templateを記述します。

プロジェクト名/
 ├ components/
 │ └ appButton.vue
 └ pages/
   └ index.vue

appButton.vue
<template>
  <div class="container mx-auto">
    <div
      class="flex items-center justify-center mx-auto w-4/5 h-12 rounded-full cursor-pointer md:w-2/4 md:h-16"
      :class="[btnColor, `hover:${colorOnHover}`]"
    >
      <p>
        <nuxt-link :to="link" class="w-full text-white text-xl md:text-2xl">{{
          text
        }}</nuxt-link>
      </p>
    </div>
  </div>
</template>

divタグのv-bind:classで、バインドすることでJavaScriptのプロパティを使用することができるようになり、配列で複数のクラスプロパティを使用できるようにする。hoverアクションは、バッククォートを含めたテンプレート文字列${` `}で表示する。
ボタンの文章はnuxt-linkの{ text }で、遷移先リンクはv-bind="link"で記述する。

2. ボタンコンポーネントの初期値設定

script側で、propsでボタンの文章、遷移先リンク、色初期値の設定を行います。
propsのタイプはすべて文字列型(String)で、それぞれデフォルト値を設定している。

appButton.vue
<script>
export default {
  props: {
    text: {
      type: String,
      default: ""
    },
    link: {
      type: String,
      default: "/"
    },
    btnColor: {
      type: String,
      default: "bg-red-300"
    },
    colorOnHover: {
      type: String,
      default: "bg-red-400"
    }
  }
};
</script>

3. ボタンの表示

表示させたいページのファイルにボタンコンポーネントを記述する。

index.vue
<template>
  <div class="container mx-auto">
    <myButton text="サービス" link="/service"></myButton>
    <myButton text="ホーム" link="/home" btnColor="bg-blue-300" colorOnHover="bg-blue-400"></myButton>
  </div>
</template>

ボタンの文章、遷移先リンク、色をコンポーネントごとに指定することができました。
サービスボタンは色を指定していないので、初期値の"bg-red-300"クラスが適用されている。


おわりに

ここまでボタンコンポーネントの作成方法についてまとめました。
コンポーネントのデータの受け渡しには、propsのValidationで関数を扱う方法やSlotではHTMLのタグの操作ができる方法もあるので、学びながら記事にしていきたいと思います!

以上、最後まで読んでいただきありがとうございました!

0
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
0
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?