vue项目笔记(15)-父子组件传值

父子组件传值

在上节中,我们已经请求到数据,现在来实现数据的传递(父→子),我们结合代码,以Recommend组件为例:

1、 首先,在data中声明数组recommendList,将请求到的数组,赋值给recommendList。

<script>
  import axios from "axios"
  import HomeHeader from "./components/Header";
  import HomeSwiper from "./components/Swiper"
  import HomeIcons from "./components/Icons"
  import HomeRecommend from "./components/Recommend"
  import HomeWeekend from "./components/Weekend"
  export default {
    name: "Home",
    data() {
      return {
        city: '',
        iconList:[],
        recommendList:[],
        swiperList:[],
        weekendList:[]
      };
    },
    components: {
      HomeHeader,
      HomeSwiper,
      HomeIcons,
      HomeRecommend,
      HomeWeekend
    },
    mounted(){
      this.getHomeInfo();
    },
    methods: {
      getHomeInfo(){
        // axios返回的结果是一个promise对象
        axios.get('/api/index.json').then(
          // 注意:这里绝对不可以写成this.getHomeInfoSucc(),否则请求的结果会是undefined
          this.getHomeInfoSucc
        )
      },
      getHomeInfoSucc(res){
        console.log(res);
        res = res.data;
        if (res.ret && res.data) {
          this.city = res.data.city;
          this.swiperList = res.data.swiperList;
          this.iconList = res.data.iconList;
          this.recommendList = res.data.recommendList;
          this.weekendList = res.data.weekendList;
        }
      }
    }
  };
</script>

2、然后,在父组件Home中引入Recommend组件,<home-recommend :list="recommendList"></home-recommend>

<template>
  <div class="home">
    <home-header :city="city"></home-header>
    <home-swiper :list="swiperList"></home-swiper>
    <home-icons :list="iconList"></home-icons>
    <home-recommend :list="recommendList"></home-recommend>
    <home-weekend :list="weekendList"></home-weekend>
  </div>
</template>

3、利用props传值,在Recommend组件中声明props,定义list类型为Array。

<script>
  export default{
    name: "HomeRecommend",
    props:{
      list: Array
    }
  }
</script>

4、最后,利用v-for指定实现数据的循环绑定,需要注意的是,这里需要使用v-for="item of list",代码如下:

<template>
  <div class="recommend">
    <div class="recommend-title">热销推荐</div>
    <ul>
      <li class="item border-bottom" v-for="item of list" :key="item.id">
        <img class="item-img"
             :src="item.imgUrl">
        <div class="item-info">
          <p class="item-title">{{item.title}}</p>
          <p class="item-desc">{{item.desc}}</p>
          <button class="item-button">查看详情</button>
        </div>
      </li>
    </ul>
  </div>
</template>

5、其他组件的数据传递与此雷同,此处不再赘述。

猜你喜欢

转载自blog.csdn.net/qq_41115965/article/details/81589438
今日推荐