LoginSignup
2
1

More than 3 years have passed since last update.

【Vue.js】for文を使って取ってきたオブジェクトのプロパティを子コンポーネントに渡す

Posted at

問題

Vue.jsでfor文を使って配列を回したが、取ってきたオブジェクトのプロパティを子コンポーネントに渡す方法がわからない

やりたいことの整理

for文で取ったtemperature内の値をTheWeatherItemコンポーネントに入れたい

▼親コンポーネント

TheToday.vue
<template>
  <div class="today">
    <TheTitle label="Today" :is-today="true" :day="displayDay()"></TheTitle>
    <div class="today-weather">
      <template v-for="(temperature, index) in temperature.todayTemperature">
        <TheWeatherItem :key="index"></TheWeatherItem>
      </template>
    </div>
  </div>
</template>

▼for文で取ってきたtemperetureの中身
スクリーンショット 2020-02-17 16.17.07.png

▼子コンポーネント

TheWeatherItem.vue
<template>
  <div class="weather-item">
    <p class="weather-item__time">Now</p>
    <img src="img/rain.png" alt="" class="weather-item__img" />
    <p class="weather-item__temp"></p>
  </div>
</template>
<script>
import { weatherMixin } from "@/mixins/weather-mixin";
export default {
  name: "TheWeatherItem",
  mixins: [weatherMixin]
};
</script>

▼現在の画面
一旦欲しい値は時間と気温の2つ(アイコン部分は後ほど修正)
スクリーンショット 2020-02-17 16.22.32.png

やってみる

子コンポーネントのpropsを追加すれば解決できそう
▼子コンポーネント修正

TheWeatherItem.vue
<template>
  <div class="weather-item">
    <p class="weather-item__time">{{ content.time }}</p>
    <img src="img/rain.png" alt="" class="weather-item__img" />
    <p class="weather-item__temp">{{ content.temperature }}</p>
  </div>
</template>

<script>
import { weatherMixin } from "@/mixins/weather-mixin";
export default {
  name: "TheWeatherItem",
  mixins: [weatherMixin],
  //props追加
  props: {
    content: {
      type: Object,
      required: true
    }
  }
};

▼親コンポーネント修正

TheToday.vue
<template>
  <div class="today">
    <TheTitle label="Today" :is-today="true" :day="displayDay()"></TheTitle>
    <div class="today-weather">
      <template v-for="(temperature, index) in temperature.todayTemperature">
        <!--contentにtemperatureを渡す-->
        <TheWeatherItem :key="index" :content="temperature"></TheWeatherItem>
      </template>
    </div>
  </div>
</template>

結果

取れたけどタイムスタンプのままだったり温度が四捨五入されていないので修正が必要
スクリーンショット 2020-02-17 16.37.16.png

修正

フィルターを作って取ってきた値にかける
スクリーンショット 2020-02-17 16.46.53.png

できた🐱

2
1
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
2
1