LoginSignup
0
1

More than 3 years have passed since last update.

v-bindの使い方。親のデータを子のテンプレートに渡す方法。

Last updated at Posted at 2020-10-26

Vueのv-bindで、親から子へのデータ受け渡しを整理。

以下のようなvueファイルを見たときに、:keyなどタグの中身(任意で設定した属性)が何を表しているのかを理解できるようになる。

<VrBtn
:key="key"
:disabled="disabled"
:command="command"
/>
export default {
  props: {
    value: { type: Boolean },
    disabled: { type: Boolean, default: false },
    command: { type: Object, required: true },
  },
}


データ受け渡しの流れ

データ受け渡しの流れは4steps。
属性に変数を入れて、その属性を親と子で受けわたす。

親:①子に渡すデータを定義
 ↓
親:②子のテンプレートタグに属性と変数を記述
 ↓
子:③propsで受け取る属性を定義
 ↓
子:④属性を指定してデータ呼び出し

▼注意点
・親から渡すデータは変数。
 ┗ ダブルクオテーションで囲むがテキストではない。
 ┗ :属性名="変数名"の形で記述。属性を子に渡す。
 ┗ : は v-bind: の省略形

・子のpropsではデータの型などを指定可能
 ┗ String:文字列、Boolean:真偽値
 ┗ required: true データの必要性
 ┗ default: false/true 真偽値のデフォルト設定


データの受け渡し例

・使うファイルは2つ
親:parent.vue
子:TmpBtn.vue (vuetifyでボタンを表示)

・実現したいこと
親で定義したデータを子のテンプレート内で呼び出す。

(親)parent.vue
<template>
  <v-app>
    <TmpBtn
    <!--②子のテンプレートタグに属性と変数を記述-->
    :bind="text"
    />
  </v-app>
</template>

<script>
import TmpBtn from "./TmpBtn"

export default {
  name: "Parent",
  components:{
    TmpBtn
  },
  data(){
    return{
      //①子に渡すデータを定義
      text:"Text form Parent"
    }
  }
}
</script>


(子)TmpBtn.vue
<template>
  <v-btn
  width="20%"
  elevation="2"
  rounded
  >
  <!--④属性を指定してデータ呼び出し-->
  {{bind}}
  </v-btn>
</template>

<script>
export default {
  props:{
    //③propsで受け取る属性を定義
    bind: {type:String},
  }
}
</script>



▼出力結果
image.png

子のテンプレートを表示したときに、無事、親のデータを受け渡すことができた。


まとめ

以下のような記述を見たら、親から子にデータを渡していることがわかる。

<VrBtn
:key="key"
:disabled="disabled"
:command="command"
/>

propsがあれば、子のテンプレートで親からデータを受け取っているなということがわかる。

export default {
  props: {
    value: { type: Boolean },
    disabled: { type: Boolean, default: false },
    command: { type: Object, required: true },
  },
}
0
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
0
1