vue 父刷新子_父组件中vuex方法更新state子组件不能及时更新并渲染的完美解决方法...
場景:
我實際用到的是這樣的,我父組件引用子組件related,父組件調用獲取頁面詳情的方法,更新了state值related,子組件根據該related來渲染相關新聞內容,但是頁面打開的時候總是先加載子組件,子組件在渲染的時候還沒有獲取到更新之后的related值,即使在子組件中watch該值的變化依然不能渲染出來子組件的相關新聞內容。
我的解決辦法:
父組件像子組件傳值,當父組件執行了獲取頁面詳情的方法之后,state值related更新,然后傳給子組件,子組件再進行渲染,可以正常獲取到。
父組件代碼:
{{ title }}
{{pubName}}
{{authorName}}
{{createAt|formatTime}}
關注
責任編輯:{{editorName}}閱讀全文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.read}}
{{item.createAt|formatTime}}
import {mapActions, mapState, mapGetters} from 'vuex'
import moment from 'moment'
export default{
data(){
return {
lists: [],
id:this.$route.params.id,
}
},
props:{
related:Array //重點是這里
},
created(){
moment.locale('zh-cn');
},
/*computed: {
...mapState({
related: state => state.newsDetails.related,
})
},*/
filters:{
formatTime(time){
return moment(time).fromNow();
},
},
methods:{
},
watch: {
related (val) {
this.lists = val;
},
'$route'(to,from){
this.id=this.$route.params.id
}
}
}
效果如圖:
總結
以上所述是小編給大家介紹的父組件中vuex方法更新state子組件不能及時更新并渲染的完美解決方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
總結
以上是生活随笔為你收集整理的vue 父刷新子_父组件中vuex方法更新state子组件不能及时更新并渲染的完美解决方法...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql模糊查询后分页_jsp模糊查询
- 下一篇: 面试mysql慢查询_剑指Offer面试