【问题标题】:Access api data in child component on ready with Vue.js准备好使用 Vue.js 访问子组件中的 api 数据
【发布时间】:2023-04-09 14:54:01
【问题描述】:

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

情况。

我正在从父组件调用我的 API,并通过道具将数据传递给我的子组件。子组件显示数据很好,但我无法在子组件的 ready 函数中访问数据。

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

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

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

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

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

我的尝试

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

问题

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

【问题讨论】:

  • 我也遇到了同样的问题,你找到解决这个问题的好办法了吗?
  • 现在我正在使用事件在我的数据准备好时进行广播

标签: javascript api components vue.js


【解决方案1】:

问题在于 DOM 已加载并准备就绪,而 AJAX 函数仍在接收数据。因此,组件上的 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'
})

【讨论】:

  • 确实是这个问题。我试图用你的想法修改我的小提琴,但它不起作用。 jsfiddle.net/kmrfkynf/5对象还是空的
  • 我添加了nextTick() 并初始化了items 数组。它现在看起来正在使用我上面的更改。
【解决方案2】:

正如@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 回调之前,不会插入组件。 done 回调在items 更改时调用(有关详细信息,请参阅watch)。因此,当调用ready 函数时,items 将具有正确的数据。

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

【讨论】:

  • 这也是一个非常好的解决方案。感谢您指出了这一点。可能比必须为我调用的每个 api 创建一个观察者更好
猜你喜欢
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 2017-01-24
  • 2016-11-16
  • 2020-07-18
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
相关资源
最近更新 更多