【Vue.js】$emitでObjectの一部だけ変更して更新する

  • 2021年10月7日
  • 2021年10月27日
  • Vue.js
  • 2000view

ここのid=1のtitleだけ変えたい。

$emitで更新する場合、

this.$emit('update:props名',更新する値)

となる為、オブジェクトを更新して親コンポーネントに渡すには一工夫が必要。

やり方

①$emitイベントの第2引数でスプレッド構文を使い、要素を書き換える

$emitの第2引数をスプレッド構文を用いると、元のpropsをコピーし、1部分を書き換える事が出来る。

例 item.idを書き換える

this.$emit('update:item', {...this.item, id: 3})
    },

②書き換える要素にindexを指定して、配列ごと書き換える

書き換え要素に[index]とする事で、配列を取得し、書き換えられる。

// itemの2要素目のテストを書き換える
// item = {
//  {id:1,value:"テスト"},
//  {id:2,value:"テスト"}
// }


const value = {id:2,value:"書き換え"}
this.$emit('update:item', {...this.item, [2]: value})
    },

まとめ

  • $emitでスプレッド構文を用いる事でオブジェクトの1部を変更出来る
  • 要素に[index]を指定すると、その順番の配列を取得、書き換え出来る

初めてweb開発の現場に入った時にVue.jsの勉強用に買った本を思い出に添付。

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Compare ×
Let's Compare! Continue shopping