当前位置:首页 » 《关注互联网》 » 正文

解决vue中父组件通过props向子组件传递数据,子组件接收不到

16 人参与  2024年05月07日 17:12  分类 : 《关注互联网》  评论

点击全文阅读


问题:父组件在挂载时向后端发起请求获取数据,然后将获取到的数据传递给子组件,子组件想要在挂载时获取数据,获取不到。

代码示例:

//父组件<template>  <div>    <HelloWorld :message="message"></HelloWorld>  </div></template><script setup>import HelloWorld from "./components/HelloWorld.vue";import { onMounted, ref } from "vue";const message = ref("1");onMounted(() => {//模拟异步请求   setTimeout(() => {    message.value = "1312";  }, 0);});</script><style scoped></style>
//子组件<template>  <div>{{message}}</div></template><script setup>import { onMounted, defineProps } from "vue";const props = defineProps(["message"]);onMounted(() => {  console.log("传递过来的数据", props.message);});</script><style scoped></style>

打印结果:props.message为空,为父组件message的初始值,但是子组件数据能渲染出来
在这里插入图片描述

原因分析:

父子组件的生命周期执行顺序如下:

加载数据渲染过程

父组件beforeCreate父组件created父组件beforeMount子组件beforeCreate子组件created子组件beforeMount子组件mounted父组件mounted

更新渲染数据

父组件beforeUpdate子组件beforeUpdate子组件updated父组件updated

销毁组件数据过程

父组件beforeUnmount子组件beforeUnmount子组件unmounted父组件unmounted

由上述加载数据渲染过程可知子组件的mounted是先于父组件的mounted,所以获取不到异步请求后获取到的数据

解决方法

方法一:使用v-if控制子组件渲染的时机

//父组件<template>  <div>    <HelloWorld :message="message" v-if="isShow"></HelloWorld>  </div></template><script setup>import HelloWorld from "./components/HelloWorld.vue";import { onMounted, ref } from "vue";const message = ref("1");const isShow=ref(false);onMounted(() => {//模拟异步请求   setTimeout(() => {    message.value = "1312";    isShow.value=true;//获取数据成功,再让子组件渲染  }, 0);});</script><style scoped></style>

方法二:使用watch对父组件传递过来的数据进行监控

//子组件<template>  <div>{{message}}</div></template><script setup>import { defineProps,watch} from "vue";const props = defineProps(["message"]);//监听传过来的数据watch(()=>props.message,()=>{ console.log("传递过来的数据", props.message);})</script><style scoped></style>

在这里插入图片描述


点击全文阅读


本文链接:http://m.zhangshiyu.com/post/104793.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最新文章

  • 抽卡后,气运之子怎么都缠上来了小说(夏挽棠)(抽卡后,气运之子怎么都缠上来了)全书+后续+结局在线阅读
  • 前传爱意随风消逝续集:全文+番外乔清浅宋轻舟:结局+番外新上热文
  • 宋昭黎陆铭绪(假如从没拥抱你)前文+全本完整阅读预售作品抢先看
  • 终章小说搬空海港!我携军舰嫁军官躺赢了完结篇(温婉历战)已更新+延伸(搬空海港!我携军舰嫁军官躺赢了)清爽版
  • 贵妻在上:废材老公来护航完结篇(贵妻在上:废材老公来护航)章节目录+章节前文(宋锦瑶霍少霆)全章无套路在线
  • 离婚后,前夫一家给我跪下了隐藏剧情_明白双宿双飞江城必读文_小说后续在线阅读_无删减免费完结_
  • 乔芊芊顾宴夜小说(乔芊芊顾宴夜)(踹了渣男后,禁欲大佬为我失控)前传+阅读全新作品预订
  • 假如从没拥抱你小说(宋昭黎陆铭绪)全本完整阅读最新章节(假如从没拥抱你)_笔趣阁
  • 特工医妃,摄政王的腹黑掌上欢前言+后续_苏清叙裴玄褚最新阅读_小说后续在线阅读_无删减免费完结_
  • 热文推荐绑定站姐系统后,我成娱乐巨头了附加(沈霁月沈暨星)(绑定站姐系统后,我成娱乐巨头了)最新章节列表
  • 爱你的事当做秘密惊天黑幕_鹿言裴禹连载_小说后续在线阅读_无删减免费完结_
  • 和前夫穿越后又重生了番外+结局(挽星阙靖安)小说在线阅读

    关于我们 | 我要投稿 | 免责申明

    Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1