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.

propsの書き方

Posted at

はじめに

Vueで親コンポーネントから子コンポーネントに値を渡すpropについて、簡単にまとめました。

Propsはプロパティを意味します。
Propsを利用することで親コンポーネントから子コンポーネントに文字列、数値、配列やオブジェクトなどの値を渡すことができます。
逆に子コンポーネントから親コンポーネントに渡すときはemitを使う。

コンポーネント間でのデータ受け渡しが頻繁に行われたり階層が増えてくる場合はVuexを使った方が便利。
Propsは読み取り専用で子コンポーネントからの編集は不可。親コンポーネントが値を持っています。


子コンポーネント propsで親コンポーネントのデータ、postを受け取り表示させる。propsは子コンポーネントに書く。
Child.vue

  <template>
  <div>
      <h4>{{ props.blogTitle }}</h4>
     <h4>{{ props.blogbody}}</h4>
  </div>
</template>

<script>

export default {
  name: "Child",
  props: ["props"],

};
</script>

親コンポーネント

Parent.vue

<template>
  <div>
   <!-- 変数の値を渡したい場合はv-bindを使用 -->
     <Child :props="post" v-for="(post, index) in sampleBlogCards" :key="index"/>
  </div>
</template>

<script>
import Child from "../components/Child";

export default {
  name: "Parent",
  components: {
    Child
  },
    data() {
    return {
         sampleBlogCards: [
        {
          blogTitle:'Blog Card 1',
          blogbody:'stock-1',
          blogDate:'May 1, 2021',
        },
         {
          blogTitle:'Blog Card 2',
          blogbody:'stock-2',
          blogDate:'May 1, 2021',
        },
         {
          blogTitle:'Blog Card 3',
          blogbody:'stock-3',
          blogDate:'May 1, 2021',
        },
          {
          blogTitle:'Blog Card 4',
          blogbody:'stock-4',
          blogDate:'May 1, 2021',
        }
      ],
    };
  },
};
</script>

違う例。

子コンポーネント。propsで親からのデータをもらう。

Child.vue
<template>
    <div>
        <p>{{ message }}</p>
    </div>
</template>
<script>
export default {
    props: ['message']
}
</script>

親コンポーネント

子コンポーネントをimportして”message”でHello Vue!!という値を子に渡している。

Parent.vue
<template>
    <div>
        <child message="Hello Vue!!"></child>
    </div>
</template>
<script>
import Child from './Child';
export default {
    components: {
        Child
    }
}
</script>

Hello Vue!!が表示される。

参考
https://www.freecodecamp.org/news/how-to-use-props-in-vuejs/
https://reffect.co.jp/vue/vue-js-master-props-for-beginner

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?