父子组件

82 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天,点击查看活动详情

1.父组件

"Math.random() > 0.4"随机生成0-1的数字,如果数字大于0.4就显示第一个组件,反之就显示第二个组件

:lists="item" 把遍历出来的每一项赋值给lists,子组件通过props接受传过来的值。

                <template>
  <div class="lists">
  遍历lists将获得的item赋值给每一个子组件
<div class="tops" v-for="(item, index) in lists" :key="item.id">
  <Oneview v-if="Math.random() > 0.4" :lists="item" />
  <Twoview v-else :lists="item" />
</div>
  </div>
  </template>

可以看到遍历出来的数组,里面给一个信息 image.png

<script>
引入axios
  import axios from "axios";
import Oneview from "./list/Oneview.vue";
 import Twoview from "./list/Twoview.vue";
 export default {
  components: { Oneview, Twoview },
 data() {
return {
  lists: [],
};
  },

页面挂载完成发送请求

  mounted() {
axios.get("http://119.45.221.185:4000/getList").then(({ data }) =>   {
  console.log(data);
  this.lists = data;
});
  },
  };
</script>

  <style scoped>
 .lists {
 margin: 0 10px;
 }
.tops {
 margin: 10px 0;
 border-bottom: 1px solid #ccc;
}
 </style>

2.子组件

①。子组件1

              <template>
   <div class="one">
 
<div style="font-weight: bold;">{{lists.title}}>{{lists.title}}</div>
<div class="img">

imgs是一个数组,遍历数组,将遍历的值赋给src

  <img v-for="(item2, index2) in lists.imgs" :key="index2" :src="item2" />
</div>
<div>{{ lists.pl}}评论&nbsp;&nbsp;&nbsp;&nbsp;{{ lists.category }}</div>
 </div>
  </template>

     <script>
  export default {
  props: ["lists"],
 };
</script>

 <style scoped>
.img img{
width: 29vw;
height: 29vw;
 }
 </style>
 

②。子组件2

        <template>
  <div class="two">
<div class="top_a">
  <div>
    <p style="font-weight: bold">{{ lists.title }}</p>
    <p>{{ lists.pl }}评论&nbsp;&nbsp;&nbsp;&nbsp;{{ lists.category }}</p>
  </div>
  <div>
    <img :src="lists.imgs[0]" alt="" />
  </div>
</div>
  </div>
  </template>

  <script>
  export default {
  props: ["lists"],
};
</script>

<style scoped>
   .top_a {
  display: flex;
 }
 .top_a div:nth-of-type(1) {
  display: flex;
 height: 29vw;
  flex-wrap: wrap;
  align-content: space-between;
 }
img {
 width: 29vw;
   height: 29vw;
 }
</style>

image.png

总结:如果不熟练的话可以先单独把页面写出来,再拆分成组件,页面数据在父元素那里的话,传值给子元素可以通过props传值(简单快捷),两个组件一个显示一个不显示的话可以通过随机数进行判断,满足条件的显示,否则就不显示。