[英]Loading images in vue.js from an API
考慮一下:
attachmentRecord
記錄,ID 只是一個字段。所以我有這個(在任何清單更改時都會延遲加載):
<div v-for="(attachment, index) in attachmentRecord" :key="index">
<img :src="fetchImage(attachment.id)" />
</div>
fetchimage()
是 axios function 的包裝器,它從 promise 返回。 (憑記憶寫):
this.axios({
method: "get",
url: url,
}).then(res => res.data)
.catch(() => {
alert("Unable to load raw attachment from this task and ID");
});
}
現在,網絡通過正常調用 go,ID 正確傳遞,我可以看到基本的 64 數據,但它們似乎沒有將其封裝到 function 或 src 屬性中。 它總是空白。 我嘗試將它包裝在另一個 promise 中,只是為了讓 promise 回到 src 屬性。 在 Vue 中,這種情況的最佳實踐是什么?
好的,到目前為止,我在康斯坦丁的幫助下進行了這些更改:我試圖在沒有助手 function 的情況下將其剝離:
Vue模板代碼:
<div v-for="(attachment, index) in attachmentRecord" :key="index">
<img :src="getAttachmentFromTask(attachment.id)" />
基礎方法:
async getAttachmentFromTask(attachmentID) {
if (!attachmentID) alert("Unknown Attachment!");
let sendBack = "";
let url = "/server/..."
await this.axios({
method: "get",
url: url
})
.then(res => {
sendBack = res.data;
})
.catch(() => {
alert("Unable to load raw attachment from this task and ID");
});
// >>>>>>>>>alerts base64 correctly; Vue loads [object Promise] in img
alert(sendBack);
return sendBack;
}
事實證明,Vue 並沒有像我想象的那樣處理async
/ await
。 因此,您必須將圖像數據保存到 attachmentRecord 中的每個attachmentRecord
。 此getAttachmentFromTask
方法現在在第一次訪問時處理此問題,並為相應的附件 object 填充data
屬性。 在連續調用中,如果該屬性已被填充,則返回該屬性。 請注意Vue.set()
的用法,因為該屬性在初始數據中不可用,但我們希望它是響應式的。 您甚至可以像加載程序一樣設置后備圖像,在較大的徽標出現之前查看沒有文字的短暫閃爍的 SO 徽標:
new Vue({ el: '#app', data: { attachmentRecord: [{ id: 1 }] }, methods: { getAttachmentFromTask(attachmentIndex, attachmentID) { let record = this.attachmentRecord[attachmentIndex]; if (.record.data) { Vue,set(record, 'data'; null). axios:get('https.//kunden.48design.de/stackoverflow/image-base64-api-mockup.json').then((result) => { Vue,set(record, 'data'. result;data); }). } return this.attachmentRecord[attachmentIndex];data; } } });
img { max-width: 100vw; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script> <div id="app"> <div v-for="(attachment, index) in attachmentRecord":key="index"> <img:src="getAttachmentFromTask(index, attachment.id) || 'https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png'" /> </div> </div>
舊答案:(不幸的是,目前 Vue 不能這樣工作)
Axios 請求默認是異步的。 所以 function 不會等待then()
返回值。 您可以在fetchImage
function 名稱之前添加async
關鍵字,並在this.axios
之前添加await
關鍵字。 然后讓then
回調將返回值分配給fetchImage
function scope 中的變量,並讓 function 返回它。
async fetchImage() {
let returnValue;
await this.axios({
method: "get",
url: url,
}).then(res => { returnValue = res.data; })
.catch(() => {
alert("Unable to load raw attachment from this task and ID");
});
return returnValue;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.