首頁  >  文章  >  web前端  >  處理父元件方法更新到子元件無法渲染

處理父元件方法更新到子元件無法渲染

php中世界最好的语言
php中世界最好的语言原創
2018-06-06 11:00:191580瀏覽

這次帶給大家處理父元件方法更新到子元件無法渲染,處理父元件方法更新到子元件無法渲染的注意事項有哪些,下面就是實戰案例,一起來看一下。

場景:

我實際用到的是這樣的,我父元件引用子元件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


效果如圖:

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

微信小程式怎樣做出彈出框功能

Vue怎麼切換國家語言

以上是處理父元件方法更新到子元件無法渲染的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn