javascript - 使用 Vue.js 访问子组件中的 api 数据

标签 javascript api components vue.js

我正在开发一个大型应用程序,在处理来 self 的 API 的数据并将其传递到我的子组件时遇到了很多麻烦。

情况。

我从父组件调用我的 API,并通过 prop 将数据传递到我的子组件。子组件可以很好地显示数据,但我无法在子组件的就绪函数中访问数据。

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

正如您在控制台中看到的那样,在子组件就绪函数中显示数据会给我一个空对象...

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

...但是子组件在我的重复中很好地渲染了对象。

所以问题是子组件在父组件的 API 调用完成之前渲染。完成后,它将数据同步到我的子组件,从而渲染得很好。

我尝试过的

从我的子组件中观看 Prop 。当 Prop “完成”时,我可以访问它。但这在尝试修改 prop 中的某些数据时给我带来了很多问题,因为它每次都会渲染。这不是我想要的解决方案。

问题

当子组件准备好时,如何确保 Prop 被填充?

最佳答案

问题在于 DOM 已加载并准备就绪,而 AJAX 函数仍在接收数据。因此,组件上的 ready 方法会在结果从服务器返回之前触发。

当数据从服务器返回时,你可以触发一个事件来告诉 child :

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'
})

关于javascript - 使用 Vue.js 访问子组件中的 api 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34219738/

相关文章:

javascript - 在 React Native 中推送 View Controller 时如何隐藏/删除默认后退按钮?

javascript - 使用 Yammer REST API 发布/创建投票

javascript - React js TypeError:this.state.list.map不是一个函数

c# - 是否可以告诉 Visual Studio 不要将源文件视为 "component"?

javascript - Rails 不显眼的 javascript - 无法加载资源

javascript - Angular 5 中 Observable 中 'this' 的范围

javascript - 如何将 DOM 元素中的任何内容传递给 $scope 中定义的函数

azure - 如何从azure graph API获取用户列表

android - 提高我的最低 API 级别的更好方法?

reactjs - React 在组件内将 prop 的一部分加粗