[英]vue.js API Call with Dynamic schema
I have used AXIOS for fetching data from my API, it takes some extra time to get the data, have used CREATED hook point to call the API.我使用 AXIOS 从我的 API 中获取数据,获取数据需要一些额外的时间,使用 CREATED 挂钩点来调用 API。
<template>
<div>
Period
{{This.GetPeriod()}}
</div>
</template>
data:function(){
APIData:{}
},
created :{
GetData:function(){
---- AXIOS get call
}
},
methods:{
GetPeriod:function(){
return this.ApiData.StartDate+":'+ApiData.EndDate
}
}
Now I am getting below exception :现在我得到以下异常:
My whole code runs 2 times.我的整个代码运行了 2 次。
{ "Banners":[{ some properties }], "Links":[{ some properties }], "Widgets":[{ properties }], "Layouts":{ "LayoutName":"Layout4", "ContentDefinitionID":"9", "PlaceHolderID":"", "DisplayOrder":"", "Type":"EmployeeLanding", "StartDate":null, "EndDate":null, "VariantID":"EFDD2115", "Status":null, "Audience":{ "Groups":[], "Segments":[ ], "PopupMode":0, "ErrorMessage":null }, "PopupMode":0, "ErrorMessage":null }
} }
The startDate and EndDate is in the Layout property so Do I need to create the schema on my Vue.js or can be managed dynamically so that it do not give exception of undefined . startDate 和 EndDate 位于 Layout 属性中,所以我需要在我的 Vue.js 上创建架构还是可以动态管理,这样它就不会出现 undefined 异常。 Also the code is running 2 times.
代码也运行了 2 次。
The created
hook you want to use is a function as you can see in the docs Lifecycle-Hooks您要使用的
created
的钩子是一个函数,您可以在文档Lifecycle-Hooks中看到
Also you could make GetPeriod a computed value as its more fitting here semantically.您也可以使 GetPeriod 成为计算值,因为它在语义上更合适。
For not getting the error you can either set default values for start and end date or before calculating the period or you can check if those are defined.为了不出现错误,您可以设置开始日期和结束日期的默认值或在计算期间之前设置默认值,或者您可以检查是否已定义这些值。 If not return a dash or an empty string.
如果不返回破折号或空字符串。
To make it more user friendly you can try having a loading state for your app, and after the xhr call is finished populate your templates and remove the loader.为了使其更加用户友好,您可以尝试为您的应用设置加载状态,并在 xhr 调用完成后填充您的模板并删除加载程序。
Example usage示例用法
<template>
<div>
Period: {{period}}
</div>
</template>
<script>
data:function(){
APIData:{}
},
created(){
this.getData();
},
methods: {
getData:function(){
---- AXIOS get call
}
},
computed:{
period:function(){
let {StartDate, EndDate} = this.ApiData;
return (StartDate && EndDate) ? `${StartDate} : ${EndDate}` : '';
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.