簡體   English   中英

使用Vue.js訪問子組件中的api數據

[英]Access api data in child component on ready with Vue.js

我正在開發一個大型應用程序,我在處理來自API的數據並將其傳遞給我的子組件時遇到了很多麻煩。

情況。

我從父組件調用我的API,並通過prop將數據傳遞給我的子組件。 子組件顯示數據就好了,但是我無法訪問子組件中ready函數中的數據。

看看: https//jsfiddle.net/kmrfkynf/3/

正如您在控制台中看到的那樣,在子組件就緒函數中顯示數據會給我一個空對象...

ready: function(){
    console.log('items from child component', this.items);
}

...但是子組件在重復中呈現對象就好了。

所以問題是在父調用API調用完成之前呈現子組件。 完成后,它會將數據同步到我的子組件,因此渲染得很好。

我試過的

從我的孩子組件中看到道具。 當道具“完整”時,我可以訪問它。 但是當嘗試修改道具中的某些數據時,這會給我帶來很多問題,因為它每次都會渲染。 這不是我想要的解決方案。

這個問題

當子組件准備好時,如何確保支撐被填充?

問題是,當AJAX函數仍在接收數據時,DOM已加載並准備就緒。 因此,組件上的ready方法在結果從服務器返回之前觸發。

您可以觸發一個事件來告訴孩子何時從服務器返回數據:

var item = Vue.extend({
    props: ['items'],
  data:function(){return{items:[]}},
  template: '<div v-for="item in items">{{ item }}</div>',
  ready: function(){

    this.$on('datahere', function(){
        alert(this.items[0].id);
      //console.log('datahere items', this.items);

    })
    //console.log('items from child component', this.items);
  }
})

Vue.component('item', item);

var items = Vue.extend({
    ready: function(){
    this.init();
  },
  data: function(){
    return {
        items: {}
    }
  },
  methods:{
    init: function(){
        this.getItems();

    },
    getItems: function(){
        this.$http.get('https://api.github.com/users/mralexgray/repos')
        .success(function(data){
          this.$set('items', data);
          this.$nextTick(function(){
                this.$broadcast('datahere', data);
          });

          console.log('items from parent components: ', this.$get('items'));
        })
    }
  },
    template: '<div class="test"><item :items.sync="items"></item></test>',
  components: {'item': item}
})

Vue.component('items', items);



var app =  new Vue({
    el: '#app'
})

正如@ Douglas.Sesar所說, item組件的ready方法在結果從服務器返回之前觸發。

要解決這個問題,您需要添加的是activate hook

var item = Vue.extend({

  activate: function(done) {
    var unwatch = this.$watch('items', function() {
      unwatch(); // teardown the watcher
      done(); // ready to insert the component
    });
  },

  props: ['items'],
  template: '<div v-for="item in items">{{ item }}</div>',
  ready: function(){
    console.log('items from child component', this.items);
  }
})

在組件插入之前調用該鈎子。 在調用done回調之前,不會插入組件。 items發生變化時,將調用done回調(有關詳細信息,請參閱watch )。 因此,當調用ready函數時, items將具有正確的數據。

https://jsfiddle.net/kmrfkynf/8/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM