在vue父组件中调用方法并传值给子组件碰到的渲染问题

今天碰到这样一个问题:

// 这是父组件
<menu-item
      :fitems="items"
    ></menu-item>
    
import MenuItem from "./MenuItem";

mounted() {
	console.log("father created");
    this.getRoute();
},
methods: {
	async getRoute() {
      const res = await listRoute();

      this.items = JSON.parse(res.rows[0].remark);
      this.routeId = res.rows[0].routeId;

      console.log(this.items, "father");
    },
}

// 这是子组件
<el-card>
      <el-tag
        @close="moveQuickEntryItem(item)"
        :key="index"
        closable
        v-for="(item, index) in fitems"
        >{{ item.meta.title }}</el-tag
      >
    </el-card>

props: {
	fitems: {
      required: true,
      type: Array
    },
}

created() {
    console.log("son created");
    console.log(this.fitems, "son");
 },

然后大家可以先想想控制台会打印出啥?
控制台打印的数据大概率不符合你的预期:

father created
son created
[], "son"  // 子组件中没有数据的空数组
[{...}], "father" // 父组件中有数据的数组

之后发现原因是因为created中的异步请求会挂起,执行其中的同步任务,等同步任务执行完毕之后就会去执行子组件中的created,而在created中挂起的异步请求则会在父组件的updated中返回,所以其中一个解决办法就是在updeted中来接收数据,另一个就是下边这个:

可以给依赖请求数据的子组件加一个标识符,也就是说等请求数据返回了再让子组件显示

<menu-item
      v-if="flag"  //加上标识符
      :fitems="items"
    ></menu-item>
    
import MenuItem from "./MenuItem";

mounted() {
	console.log("father created");
    this.getRoute();
},
methods: {
	async getRoute() {
      const res = await listRoute();

      this.items = JSON.parse(res.rows[0].remark);
      this.routeId = res.rows[0].routeId;
	  this.flag = true // 数据返回后让子组件显示
      console.log(this.items, "father");
    },
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值