当Promise解决并将道具传递给嵌套子代时如何更新Vue组件

问题描述

我有父级和子级组件。父母的数据在ajax调用后被填充,我想将其作为道具传递给孩子。

我尝试了不同的解决方案,我将发布两个解决方案,但仍无法正常工作:能否请您指出错误

该组件确实对更改做出反应。我还需要确保将道具正确传递给child及其嵌套的孩子。

尝试:

  • 如果我不使用'v-if'指令,则会因:query为 传递为null。

  • 所以我使用v-if(请参见下面的版本) 并更新渲染,但它不会做出反应并保持空白(甚至 尽管数据已正确更新)。

  • 我还尝试了在不使用计算值的情况下初始化查询数据 v-if指令,因为毕竟我只需要缓存结果 的前提。

  • 我也尝试在总线上发出事件,但是该组件没有 反应。

  • 最后,我尝试通过使用 :key(例如:key="ready")应使组件在 :key更改。但仍然没有效果

模板:

<template>
  <div v-if="isLoaded()">
      <input>
      <metroline></metroline>
      <grid :query="query"></grid>
  </div>
</template>

脚本:

export default {

data() {
  return {
    ready : false,query : null
  }
},components : {
  metroline : Metroline,grid : Grid
},methods: {

    isLoaded() {
      return this.ready
    },firstQuery( uid,limit,offset) {

      var url = // my url
      
      // using Jquery to handle cross origin issues,solving with jsonp callback...
      
      return $.ajax({
        url : url,dataType: 'jsonp',jsonpCallback: 'callback',crossDomain: true 
        
        })

    }

},created() {
  var vm = self;

  this.firstQuery(...)
      .then(function(data){
                 this.query = data;
                 console.log('firstQuery',this.query);

                 // attempts to pass through the query
                 // bus.$emit('add-query',this.query);

                 this.ready = true;
                 self.isLoaded(); // using a self variable,temporarily,jquery deferred messed up with this; however the this.query of vue instance is properly updated
                 
            })
}

}

解决方法

在创建的钩子中,将组件实例this分配给一个名为that的变量,并在回调内访问它,因为在回调中,您不在vue组件上下文(this)中:


created() {
  var vm = self;
  var that=this;
  this.firstQuery(...)
      .then(function(data){
                 that.query = data;
                 console.log('firstQuery',this.query);

              

                 that.ready = true;
                 self.isLoaded(); 
            })
}
}