LoginSignup
0
0

More than 1 year has passed since last update.

【学習記録⑤】propsを用いて親コンポーネントから子コンポーネントに値を渡す。

Posted at

はじめに

Vue.jsを最近勉強し始めたので学んだ文法などを備忘録としてメモしていこうと思います。
今回は前回の学習記録の記事で作成した挨拶アラートを返却するコードを少し改良し、親コンポーネントから子コンポーネントへ値を渡す処理に変更したいと思います。

サンプルコード

前回の記事ではMorning.vue, Afternoon.vue, Evening.vueそれぞれに挨拶文を書いていましたが、今回はそれらのvueファイルの親コンポーネントであるApp.vueから値を渡しています。
v-bind属性を用いてtemplateタグにそれぞれ挨拶文を渡しています。

App.vue
<template>
  <div>
    <morning :message="morningMessage"></morning>
    <afternoon :message="afternoonMessage"></afternoon>
    <evening :message="eveningMessage"></evening>
  </div>
</template>

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

export default {
  data(){
    return {
      morningMessage: "おはよう~!",
      afternoonMessage: "こんにちは~!",
      eveningMessage: "こんばんは~!"
    }
  },
  components: {
    Morning,
    Afternoon,
    Evening
  }
}
</script>

挨拶文を受け取る子コンポーネントは以下のような感じでpropsプロパティで受け取っています。
(Afternoon.vue, Evening.vueも同様)

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

<script>
export default {
    props:["message"],
    methods:{
        greeting(){
            alert(this.message);
        }
    }
};
</script>

出力結果

以下のようにボタンを押すとApp.vueから渡した挨拶文がアラートで出力されます。
動作は前回の記事と同じです。
pic.png

おわりに

コンポーネント、触ってみましたが良い感じですね!
次は子コンポーネントから親コンポーネントに値を渡す学習をしたいと思います。

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