13
6

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 5 years have passed since last update.

【Vue.js】Vueのナレッジ

Last updated at Posted at 2019-11-14

Vueのナレッジ

  1. オブジェクトのプロパティを子コンポーネントに渡す
  2. 子コンポーネントに渡したデータの変更を親コンポーネントに反映する

オブジェクトのプロパティを子コンポーネントに渡す

下記のようなオブジェクトのデータを子コンポーネントに渡す時、方法はおおよそ2パターン!

boardboardTitleを子コンポーネントで表示させたい:writing_hand:

"board": {
  "boardTitle": "11/12 TODO",
  "todos": []
}

パターン① オブジェクトを省略記法を使って渡す

親コンポーネント

<board-index v-bind="board"/>

子コンポーネント(BoardIndex.vue)

<template>
  <div>{{ boardTitle }}</div>
</template>

<script>
export default {
  props: {
    boardTitle: {
      type: String,
      required: true
    },
    todos: {
      type: Array
    }
  }
}
</script>

パターン② オブジェクトをそのまま渡す

親コンポーネント

<board-index :board="board"/>

子コンポーネント(BoardIndex.vue)

<template>
  <div>{{ board.boardTitle }}</div>
</template>

<script>
export default {
  props: {
    board: {
      type: Object,
      default: () => ({
        boardTitle: '',
        todos: []
      }),
      required: true
    }
  }
}
</script>

別にオブジェクトのプロパティを個々にバインドさせる方法もあります。
場面によって使い分けることができそうです。

話が少し逸れますが、パターン②でboarddefaultを関数で返しています。
これは、
propsのデフォルト値に指定したオブジェクトや配列は、参照が共有される
ことを防ぐためです。

参照が共有されてしまうと、複数のvueインスタンスが同一のオブジェクトを参照し、同一のオブジェクトに変更を加えてしまう状況が発生します。

子コンポーネントに渡したデータの変更を親コンポーネントに反映する

親から子へpropsでデータを渡したとき、
子側でそのpropsデータを直接変えようとするとvueに怒られてしまいます。

では、どうすればいいか、備忘録でまとめておきます。

親コンポーネント

<child-component v-model="parentData"/>

子コンポーネント(ChildComponent.vue)

<script>
export default {
  props: {
    parentData: {
      type: String,
      default: ''
    }
  },
  computed: {
    inputData: {
      get() {
        return this.parentData
      },
      set(newVal) {
        this.$emit('input', newVal)
      }
    }
  }
}

</script>

親から受け取ったpropscomputedを通して別名のプロパティinputDataとして受け取り、子側でinputDataに変更があった場合、set関数で新しい値を取得して親に返します。

$emitinputイベントを送ることで親のv-modelの値にデータがバインドされます。

これができるのは、v-model (= v-on:inputv-bind:value)で双方向データバインディングを行っているためですね。

13
6
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
13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?