我一直在尝试使用 axios 用 Vue 加载数据,但是得到了 Undefined 错误。我很确定我的代码没有任何问题,因为它可以与另一个人一起使用。我认为问题是在 axios 有机会获取数据之前页面就被渲染了。
async editGoods(oldGoods) {
oldGoods.property1 = await this.$http.loadData("/item/someporperty/" + oldGoods.id);
oldGoods.property2 = await this.$http.loadData("/item/otherproperties/list?id=" + oldGoods.id);
this.isEdit = true;
this.show = true;
this.oldGoods = oldGoods;
}
下面是我的 axios 配置
import Vue from 'vue'
import axios from 'axios'
import config from './config'
axios.defaults.baseURL = config.api;
axios.defaults.timeout = 2000;
axios.loadData = async function (url) {
const resp = await axios.get(url);
return resp.data;
}
Vue.prototype.$http = axios;
这是我不断收到的错误消息:
vue.esm.js?efeb:1741 TypeError: Cannot read property 'length' of undefined
at eval (eval at ./node_modules/vue-loader/lib/template-compiler/index.js?
{"id":"data-v-c02e22a2","hasScoped":true,"transformToRequire":{"video":
["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":
{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?
type=template&index=0!./src/pages/item/GoodsForm.vue (4.js:276),
<anonymous>:332:47)
at Proxy.renderList (vue.esm.js?efeb:3705)
at Proxy.render (eval at ./node_modules/vue-loader/lib/template-
compiler/index.js?{"id":"data-v-
c02e22a2","hasScoped":true,"transformToRequire":{"video":
["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":
{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?
type=template&index=0!./src/pages/item/GoodsForm.vue (4.js:276),
<anonymous>:320:23)
at VueComponent.Vue._render (vue.esm.js?efeb:4544)
at VueComponent.updateComponent (vue.esm.js?efeb:2788)
at Watcher.get (vue.esm.js?efeb:3142)
at Watcher.run (vue.esm.js?efeb:3219)
at flushSchedulerQueue (vue.esm.js?efeb:2981)
at Array.eval (vue.esm.js?efeb:1837)
at MessagePort.flushCallbacks (vue.esm.js?efeb:1758)
可以看一下完整代码here和 here 。 GoodsForm.vue 是正在呈现的表单。
已经尝试了好几天了,有人知道如何处理这个问题吗?
最佳答案
如果您想在 axios 获取数据后立即显示数据,一种方法是根据数据模型的值在组件中添加 if 条件。就像这个一样。
在您的数据中,您可以声明新数据,比如说 is_load
data() {
return {
is_loaded:false
}
}
现在,在您的组件中,您应该应用一个条件来防止在 axios 未完成获取时加载组件。像这样
<template>
<div v-if="is_loaded">
...
...
</div>
</template>
然后在你的 axios 中,你可以将 is_load 的值更改为 true 来加载你的组件,因为 axios 已经获取了你的数据。像这样
axios.get('api endpoint', {})
.then(({data}) => {
...
...
this.is_loaded = true
);
注意:当您已经通过响应完成数据模型的初始化时,您必须将其设置为 true。
关于java - axios 加载数据的速度不够快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870858/