0
0

More than 1 year has passed since last update.

【学習記録④】コンポーネントを用いて挨拶アラートを出してみる。

Posted at

はじめに

Vue.jsを最近勉強し始めたので学んだ文法などを備忘録としてメモしていこうと思います。
前回Vue CLIを用いてVueプロジェクトを立ち上げたので、今回はコンポーネントを作ってみました。

フォルダ構成

pic.png
componentsフォルダにてそれぞれの挨拶を返却するコンポーネントを作成しており、それらをApp.vueが受け取ってindex.htmlで出力しているという流れになっています。

サンプルコード

以下はMorning.vueの中身です。Afternoon.vueとEvening.vueの中身も挨拶部分以外は同じ作りになっています。

Morning.vue
<template>
  <div>
      {{ message }}
      <button @click="greeting">おはようボタン</button>
  </div>
</template>

<script>
export default {
    data() {
        return {
            message: 'おはよう~!'
        }
    },
    methods:{
        greeting(){
            alert(this.message);
        }
    }
};
</script>

それぞれのコンポーネントを以下のApp.vueで定義しています。

App.vue
<template>
  <div>
    <morning></morning>
    <afternoon></afternoon>
    <evening></evening>
  </div>
</template>

<script>
import Morning from './components/Morning.vue';
import Afternoon from './components/Afternoon.vue';
import Evening from './components/Evening.vue';

export default {
  components: {
    Morning,
    Afternoon,
    Evening
  }
}
</script>

出力結果

上記のコードでnpm run serveを実行するとアプリが立ち上がり、ボタンをクリックすると以下のように設定したアラートが出力されます。
(以下は「こんにちは」ボタンをクリックしたとき)

pic1.png

おわりに

簡単ではありますがVue.jsのコンポーネントを触ってみました!
自分でコンポーネントを作って親子関係にまとめていけるのは大規模なアプリを作る上ではとても助かりますね!

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