Axios 赋值问题:子组件 props接收一个数组 如何在setup里打印出来

来源:3-9 vue3 响应式对象的新花样

班大人

2020-10-28

父组件

<template>
  <div class="home">
    <NavBar msg="视频频道" openLeft="0" />
    <VanSwipe :hj="homejson.advertisement" :code="num" />
    <Category :hj="homejson.Navigation" />
  </div>
</template>

<script>
import VanSwipe from "@/components/VanSwipe.vue";
import NavBar from "@/components/NavBar.vue";
import Category from "@/components/Category.vue";
import { videochannel } from "@/api/api"; //封装好的Axios 调用API
export default {
  name: "Home",
  components: {
    VanSwipe,
    NavBar,
    Category,
  },
  data() {
    return {
      active: 1,
      homejson: [],
      num: 10
    };
  },
  methods: {
    async loadrule() {
      await videochannel()
        .then(res => {
          console.log(res.data.data);
          this.homejson = res.data.data;
          this.num = res.data.code;
        })
        .catch(err => console.log("失败了" + err));
    }
  },
  created() {
    this.loadrule();
  }
};
</script>
 

子组件

<template>
  <div class="vsbanner">
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img :src="image" />
        <div>{{hj}}</div>
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script lang="ts">
import { ref, computed, defineComponent, reactive, toRefs, watch } from "vue";

export default  {
  props: {
    hj: [Array,Object],
    code: Number
  },
  setup(props, context) {
    console.log('props:',{...props}) // props: {hj: undefined, code: 10}
    console.log('context.attrs:', {
      ...context.attrs,
    })
    const state = reactive({
      images: [
        require("@/assets/banner1.jpg"),
        require("@/assets/banner2.jpg"),
        require("@/assets/banner3.jpg")
      ]
    });
    return {
      ...toRefs(state)  
    };
  }
 
};
</script>
 
写回答

1回答

张轩

2020-10-29

同学可以使用 watch 来监控 props 的变化,在子组件中 watch(props, (newProps) => { }) 

0
2
班大人
非常感谢!
2020-10-29
共2条回复

Vue3 + TS 仿知乎专栏企业级项目

带你完成前后端分离复杂项目,率先掌握 vue3 造轮子技能

3142 学习 · 2313 问题

查看课程