LoginSignup
0
0

More than 3 years have passed since last update.

【Vue】コンポーネント間のデータとメソッドの受け渡し

Last updated at Posted at 2020-09-26

はじめに

Vueの基礎的な部分、コンポーネント間のデータの受け渡しの備忘録。
親コンポーネントから子コンポーネントへのデータ受け渡しについて。
また、親コンポーネントのメソッドを子コンポーネントで利用する方法も載せた。

なお、デザインテンプレートにvuetifyを使っている。

環境

  • vue: 2.6.10
  • vuetify: 2.1.0

サンプルコード

親コンポーネント

parentComponent.vue
<template>
  <v-card>
    <child-component
      :users
      :teamId
      @showList="showUserList"
    />
  </v-card>
</template>

<script>
import childComponent from "@/components/molcules/childComponent"

export default {
  components: {
    "child-component": childComponent,
  },
  data() {
    return {
      users: [
        "Alice",
        "Bob",
      ],
      teamId: 3,
    }
  },
  methods: {
    showUserList(item) {
      console.log("showUserList: " + item)
    },
  },
}
</script>

<child-component>タグ内の:users:teamIdの記述で、親コンポーネントのusersteamIdを子コンポーネントに渡している。

また、同じ<child-component>タグ内の@showList="showUserList"で、親コンポーネントのshowUserListメソッドを子コンポーネントのshowListメソッドに渡している。

子コンポーネント

childComponent.vue

<template>
  <v-card>
    {{ teamId }}
    <v-list
      v-for="(user, index) in users"
      :key="index"
    >
      {{ user }}
    </v-list>
    <v-btn
      @click="showList"
    >
    </v-btn>
  </v-card>
</template>

<script>
export default {
  props: {
    users: {
      type: Array,
      required: false,
      default: () => []
    },
    teamId: {
      type: Number,
      required: true,
      default: () => 0
    }
  },
  methods: {
    showList(item) {
      this.$emit("showUserList", item)
    },
  },
}
</script>

props内にusersを記述することで親コンポーネントのusersを、teamIdを記述することでteamIdを受け取っている。
usersはArray型なのでtype: ArrayteamIdはNumber型なのでtype: Numberとしている。
さらにrequireddefaultも記しているが、他にも細かく追記したり簡略化して書いたりできる。
詳しくは公式ドキュメントを参考に。

おわりに

他にも、子コンポーネントのメソッドを親コンポーネントで使うrefについてもそのうち本記事に追記するかもしれない。

参考

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