博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
父组件中vuex方法更新state,子组件不能及时更新并渲染的解决方法
阅读量:7227 次
发布时间:2019-06-29

本文共 3155 字,大约阅读时间需要 10 分钟。

场景:

我实际用到的是这样的,我父组件引用子组件related,父组件调用获取页面详情的方法,更新了state值related,子组件根据该related来渲染相关新闻内容,但是页面打开的时候总是先加载子组件,子组件在渲染的时候还没有获取到更新之后的related值,即使在子组件中watch该值的变化依然不能渲染出来子组件的相关新闻内容。

我的解决办法:

父组件像子组件传值,当父组件执行了获取页面详情的方法之后,state值related更新,然后传给子组件,子组件再进行渲染,可以正常获取到。

父组件代码:

    
  
import { Toast } from 'mint-ui';  import {mapState} from 'vuex'  import Related from './Related.vue'  import moment from 'moment';  export default{    name:"NewsDetails",    components:{      Related,    },    data(){      return {        id:this.$route.params.id,        topicType:"news",        contentStatus:false,        curHeight:0,        bodyHeight:5000,        hotCommentScrollTop:0      }    },    created(){      this.id=this.$route.params.id;      this.fetchData();      moment.locale('zh-cn');    },    mounted(){      setTimeout(()=>{        this.contentToggle();      },500)    },    watch: {      '$route'(to,from){        this.id=this.$route.params.id;        this.fetchData();      }    },    computed: {      ...mapState({        title: state => state.newsDetails.title,        authorName: state => state.newsDetails.authorName,        pubNews: state => state.newsDetails.pubNews,        pubName: state => state.newsDetails.pubName,        editorName: state => state.newsDetails.editorName,        createAt: state => state.newsDetails.createAt,        content: state => state.newsDetails.content,        myFavourite: state => state.newsDetails.myFavourite,        related: state => state.newsDetails.related,      })    },    filters:{      formatTime(time){        return moment(time).fromNow();      },    },    methods:{      fetchData(){        this.$store.dispatch('getDetails',this.id);      },      follow(){        Toast('登录后进行关注');        this.$router.push("/login");      },      contentToggle(){        this.curHeight=this.$refs.bodyFont.offsetHeight;        if(parseFloat(this.curHeight)>parseFloat(this.bodyHeight)){          this.contentStatus=true;        }else{          this.contentStatus=false;        }//        this.hotCommentScrollTop=this.$refs.hotComment.height;        console.log(this.hotCommentScrollTop);      },    }  }

子组件related.vue

效果如图:

 

转载于:https://www.cnblogs.com/beileixinqing/p/8931730.html

你可能感兴趣的文章
Discuz! X2.5:文件目录结构
查看>>
我的友情链接
查看>>
TCP/IP协议及首部初了解
查看>>
防火墙iptables
查看>>
CUDA搭建
查看>>
memcached与PostgreSQL缓存命中机制
查看>>
百度地图路线检索(3)
查看>>
linux netstat 命令详解
查看>>
对前几篇blog的环境等的补充说明
查看>>
Curl命令使用解析大全
查看>>
MySQL日期函数
查看>>
【00】Effective Java
查看>>
.NET重构—单元测试重构
查看>>
SMB简介sabma服务(一)
查看>>
ANT简明教程
查看>>
Eclipse Luna WTP 与 Tomcat 8 的整合存在一个很头疼的 Bug
查看>>
小数在计算机里面的存放
查看>>
数据结构中的各种树简单解释
查看>>
我的朗科运维第七课
查看>>
CentOS的进程管理二
查看>>