Quantcast
Channel: 配列タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 834

【Vue.js】Vue.jsで、forEachを使う時の注意点

$
0
0

Vue.jsで使うthis.dataと、forEach文を活用するときは、注意が必要という記事になります。

そもそもforEach文とは

// 配列を繰り返すoffices.forEach(function(office){console.log(office)})// 繰り返す配列を、thisで取得するoffices.forEach(function(office){console.log(this)},offices)

第一引数にはコールバック関数を、第二引数には繰り返す配列を定義することで、thisとして取得できる。

結論:forEachのthisと、Vue.jsのthisは別物

forEach文内でのthisは、繰り返す配列のことを指してしまうので、直接格納することができない

// エラーになるoffices.forEach(function(office){this.array.push(office)})

配列の要素を、this.dataの配列に格納したい

以下のような、Vueインスタンスのデータがあるとする。

data(){return{holidays:[],}}

そして、以下のレスポンスデータを取得して、Vueインスタンスのデータに格納したい。

[{"id":1,"name":"owada""regular_holidays":[{"id":1,"holiday":"mon"},{"id":2,"holiday":"tue"},・・・省略],},・・・省略]

配列の中のオブジェクトの中の配列の要素を、格納したい時

つまり、"regular_holidays"の要素群をthis.dataに格納する

this.holidays=res.data.regular_holidays.map((day)=>day.holiday);

配列の中のオブジェクトの中の配列の中のオブジェクトの値を、格納したい時

つまり、"regular_holidays"の要素のオブジェクトキーである"holiday"this.dataに格納する

constholidays=[];this.offices.forEach(function(office){office.regular_holidays.forEach(function(day){holidays.push(day.holiday);});});this.holidays=holidays;

forEach内で、this.dataを取得できないので、うまく工夫する必要がある。


Viewing all articles
Browse latest Browse all 834

Trending Articles