Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 等待Vue.js中的Ajax响应数据_Javascript_Vue.js_Axios - Fatal编程技术网

Javascript 等待Vue.js中的Ajax响应数据

Javascript 等待Vue.js中的Ajax响应数据,javascript,vue.js,axios,Javascript,Vue.js,Axios,我有一个Vue组件,我正在尝试使用axios从API获取一些数据 <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } from '../js/custom.js'; export default { nam

我有一个Vue组件,我正在尝试使用axios从API获取一些数据

<template>
    <div>
        This is Default child component
        {{tools[0].name}}
    </div>
</template>

<script>
import { CustomJS } from '../js/custom.js';

export default {
  name: 'HomeContent',
  props: {
    tools: []
  },
  methods: {
      fetchData() {
        const customJs = new CustomJS();
        return customJs.getTools();
      }
  },
  created() {
    this.tools = this.fetchData(); //preferably need to wait here wait for response
  }
}
</script>

问题是,
{{tools}
未定义,因为
getTools()
需要一些时间才能返回响应数据。如何等待响应数据然后返回?

尝试下面的代码:这样代码只有在实际加载时才会呈现

<div v-if="tools">
    This is Default child component
    {{tools[0].name}}
</div>

这是默认的子组件
{{tools[0].name}

您需要返回请求中的承诺

<template>
<div>
    This is Default child component
    {{tools[0].name}}
</div>
</template>

<script>
import { CustomJS } from '../js/custom.js';

export default {
  name: 'HomeContent',
  props: {
      tools: []
  },
  methods: {
      fetchData() {
         const customJs = new CustomJS();
         return new Promise((resolve, reject) => {
             customJs.getTools()
                 .then(res => resolve(res))
                 .catch(err => reject(err))
        })
     }
  },
  created() {
      this.fetchData().then(res => {
         this.tools = res);
      } //preferably need to wait here wait for response
    }
   }
 </script>

这是默认的子组件
{{tools[0].name}
从“../js/custom.js”导入{CustomJS};
导出默认值{
名称:“HomeContent”,
道具:{
工具:[]
},
方法:{
fetchData(){
const customJs=new customJs();
返回新承诺((解决、拒绝)=>{
customJs.getTools()
。然后(res=>resolve(res))
.catch(错误=>拒绝(错误))
})
}
},
创建(){
this.fetchData().then(res=>{
这意味着,工具=res);
}//最好在这里等待响应
}
}

尝试检索挂载数据

    <template>
    // try adding this condition on div element.
                <div v-if="tools.length">
                    This is Default child component
                    {{tools[0].name}}
            </div>
        </template>

        <script>
        import { CustomJS } from '../js/custom.js';

        export default {
          name: 'HomeContent',
          props: {
            tools: []
          },
          methods: {
              fetchData() {
                const customJs = new CustomJS();
                return customJs.getTools();
              }
          },
          mounted: function () {
            this.tools = this.fetchData();    
            // or    
            // const customJs = new CustomJS();
            // this.tools =  customJs.getTools();
          }
        }
        </script>

//尝试在div元素上添加此条件。
这是默认的子组件
{{tools[0].name}
从“../js/custom.js”导入{CustomJS};
导出默认值{
名称:“HomeContent”,
道具:{
工具:[]
},
方法:{
fetchData(){
const customJs=new customJs();
返回customJs.getTools();
}
},
挂载:函数(){
this.tools=this.fetchData();
//或
//const customJs=new customJs();
//this.tools=customJs.getTools();
}
}

您要做的是将getTools函数定义为如下承诺:

getTools (id = 0) {
  return new Promise((resolve, reject) => {
    this.apiTool += (id > 0) ? id : '';
    axios.get(this.apiTool, {
    })
    .then(function (response) {
        console.log(response.data);
        resolve(response.data);
    })
    .catch(function (error) {
        console.log(error);
        reject(error)
    });
  })
}
然后,您可以在组件代码中使用它,如下所示:

<template>
    <div>
        This is Default child component
        {{tools[0].name}}
    </div>
</template>

<script>
import { CustomJS } from '../js/custom.js';

export default {
  name: 'HomeContent',
  props: {
    tools: []
  },
  methods: {
      fetchData() {
        const customJs = new CustomJS();
          customJs.getTools().then((result) => {
            return result;
          }
        )

      }
  },
  created() {
    this.tools = this.fetchData(); //preferably need to wait here wait for response
  }
}
</script>

这是默认的子组件
{{tools[0].name}
从“../js/custom.js”导入{CustomJS};
导出默认值{
名称:“HomeContent”,
道具:{
工具:[]
},
方法:{
fetchData(){
const customJs=new customJs();
customJs.getTools().then((结果)=>{
返回结果;
}
)
}
},
创建(){
this.tools=this.fetchData();//最好在此处等待响应
}
}
或使用异步/等待:

<template>
    <div>
        This is Default child component
        {{tools[0].name}}
    </div>
</template>

<script>
import { CustomJS } from '../js/custom.js';

export default {
  name: 'HomeContent',
  props: {
    tools: []
  },
  methods: {
      async fetchData() {
      const customJs = new CustomJS();
      return await customJs.getTools()  
      }
  },
  created() {
    this.tools = this.fetchData(); //preferably need to wait here wait for response
  }
}
</script>

这是默认的子组件
{{tools[0].name}
从“../js/custom.js”导入{CustomJS};
导出默认值{
名称:“HomeContent”,
道具:{
工具:[]
},
方法:{
异步获取数据(){
const customJs=new customJs();
return wait customJs.getTools()
}
},
创建(){
this.tools=this.fetchData();//最好在此处等待响应
}
}

这是默认的子组件
{{tools[0].name}
从“../js/custom.js”导入{CustomJS};
导出默认值{
名称:“HomeContent”,
道具:{
工具:[]
},
数据:函数(){
返回{
isGetTools:错误
}
},
方法:{
fetchData(){
const customJs=new customJs();
this.tools=customJs.getTools();
this.isGetTools=true;
}
},
创建(){
this.fetchData();//最好在此处等待响应
}
}

尝试在div中添加v-if,并在从AXIOS获得结果后将isGetTools更新为true。通常,我使用加载程序向用户显示请求正在进行中

<div v-if="loading">
  <loader /> //a loader component
</div>

<div v-else>
  // show the template since request finished
</div>
如果您不喜欢上述方式,您可以在进入前使用
,以便仅在请求完成时加载路由:

{
  path: '/my-route',
  component: YourComponent,
  props: true,
  beforeEnter (to, from, next) {
    axios.get('api-request')
     .then(response => {
      to.params.data = response //we pass data through props to the component
      next()
     })
  }
}

我不知道为什么这个问题会出现在我的“时间表”中,而且还没有得到公认的答案,所以我还是会回答的。问题似乎在于理解JS中异步代码的OP。以下是使其更好的修复方法(共3个):


{{tools[0].name}
//I.使用v-if/v-else有条件地显示数据,在Vue 3中,将有另一个称为“悬念”的功能来执行这些操作:https://vueschool.io/articles/vuejs-tutorials/suspense-new-feature-in-vue-3/
这是默认的子组件
从“../js/custom.js”导入{CustomJS};
导出默认值{
名称:“HomeContent”,
道具:{
工具:[]
},
方法:{
异步获取数据(){
const customJs=new customJs();
this.tools=await customJs.getTools();
//II.OP向这个.tools分配了承诺,这个.tools根本没有分配给任何实际数据,因为:
//1.getTools()未返回任何数据
//2.即使它返回了数据,在分配给this.tools之前,它也没有得到承诺解决(通过wait/then)
}
},
创建(){
这是fetchData();
}
}
异步getTools(id=0){
this.apiTool+=(id>0)?id:“”;
试一试{
const response=await axios.get(this.apiTool,{});
console.log(response.data);
返回响应数据;
//III.OP根本没有返回任何获取的数据,它只是调用API,然后什么也不做。所有返回都是在arrow函数中返回的,实际函数getTools没有得到任何返回
}
捕捉(错误){
console.log(错误)
}
},

如果要等待请求发出,可以在getTools()中使用同步http请求complete@SagarTamang不,不是个好主意
sync
已被弃用,请不要建议人们使用随时可能消失的功能。您需要等待什么,。。你能不能不要只做->
这个.fetchData()。然后(…
?@Keith好的,我会记在心里。非常感谢。我在这里得到了一个部分解决方案-还可以在getTo中从axios调用返回承诺
<div v-if="loading">
  <loader /> //a loader component
</div>

<div v-else>
  // show the template since request finished
</div>
export default {
  data: () => ({
    loading: false
  }),

  created() {
   this.loading = true
   axios.get('api') //your request
   .then(response => console.log(response))
   .finally(() => (this.loading = false)) //when the requests finish
  }

}
{
  path: '/my-route',
  component: YourComponent,
  props: true,
  beforeEnter (to, from, next) {
    axios.get('api-request')
     .then(response => {
      to.params.data = response //we pass data through props to the component
      next()
     })
  }
}