8
6

More than 3 years have passed since last update.

Vueオブジェクトの値渡し

Last updated at Posted at 2020-03-16

今回の問題

vueオブジェクトの代入が参照渡しになっていることによる、影響の問題

vue
<div v-for="item in items">
  <button @click="copy(item)">{{ item.title }}</button>
</div>

data(() => {
  items: [],
  copyItem: {} // dataに定義しているのは子コンポーネントで編集した値が欲しいから
}),

methods: {
  copy(item) {
    // 参照渡しになっているので、参照元のデータも変更される
    this.copyItem = item
    /** 以降、this.copyItemをいじる */
  }
}

解決

公式ドキュメントに書いてた

JavaScript のオブジェクトと配列は、参照渡しされることに注意してください。参照として渡されるため、子コンポーネント内で配列やオブジェクトを変更すると、 親の状態へと影響します。

js
data(() => {
  items: [],
  copyItem: {} // dataに定義しているのは子コンポーネントで編集した値が欲しいから
}),

methods: {
  copy(item) {
    // 値渡しがされるので、元データに影響は出ない
    this.copyItem = Vue.util.extend({}, item);
  }
}
8
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
8
6