请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

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

父组件

<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回答

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

0 回复 有任何疑惑可以回复我~
  • 提问者 班大人 #1
    我使用监听,但我的轮播图组件就不会轮播了,只有图,
    我写成这样就可以了,但后台报错length的错误,功能是好了
      setup(props, context) {
        console.log("props:", { ...props });
        console.log("context.attrs:", {
          ...context.attrs
        });
    
        const state = reactive({
          images: computed(() => {
            return props.hj.length;
          }),
          double: computed(() => {
            return props.hj;
          })
        });
        // watchEffect(()=> {
        //   console.log(props.hj, "改变");
        //   state.images = props.hj;
        // });
    
        return {
          ...toRefs(state) //将reactive转化为ref
        };
      }
    回复 有任何疑惑可以回复我~ 2020-10-29 10:16:38
  • 提问者 班大人 #2
    非常感谢!
    回复 有任何疑惑可以回复我~ 2020-10-29 10:31:27
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信