父组件中vuex方法更新state子组件不能及时更新并渲染的完美解决方法

网友投稿 376 2023-02-07


父组件中vuex方法更新state子组件不能及时更新并渲染的完美解决方法

场景:

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

我的解决办法:

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

父组件代码:

{{ title }}

{{pubName}}

{{authorName}}

{{createAt|formatTime}}

关注

    

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

{{item.title}}

打开唐人家

置顶

{{item.createAt|formatTime}}

效果如图:

总结

以上所述是给大家介绍的父组件中vuex方法更新state子组件不能及时更新并渲染的完美解决方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot使用Druid数据源的配置方法
下一篇:java写卷积神经网络(CupCnn简介)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~