【发布时间】:2019-09-20 04:03:31
【问题描述】:
我正在尝试使用 ImageCache NativeScript Core 模块从缓存中保存和加载图像,但它不起作用。
<template>
<Page>
<StackLayout>
<Image v-for="exampleImage in exampleImages" :src="getCachedImage(exampleImage.url)"/>
</StackLayout>
</Page>
</template>
<script>
import * as imageCache from 'tns-core-modules/ui/image-cache'
import * as imageSource from 'tns-core-modules/image-source'
export defualt {
data() {
return {
exampleImages: [
{url: 'https://image.tmdb.org/t/p/w600_and_h900_bestv2/kY2c7wKgOfQjvbqe7yVzLTYkxJO.jpg'},
{url: 'https://image.tmdb.org/t/p/w600_and_h900_bestv2/svIDTNUoajS8dLEo7EosxvyAsgJ.jpg'},
{url: 'https://image.tmdb.org/t/p/w600_and_h900_bestv2/A7XkpLfNH0El2yyDLc4b0KLAKvE.jpg'},
]
}
},
methods: {
getCachedImage(imgUrl) {
const cache = new imageCache.Cache();
cache.enableDownload();
const image = cache.get(imgUrl);
let cachedImageSource;
if (image) {
console.log('getting image from cache')
cachedImageSource = imageSource.fromNativeSource(image)
} else {
console.log('downloading image, setting it in cache, and getting from cache')
cache.push({
key: imgUrl,
url: imgUrl,
completed: (image, key) => {
if (imgUrl === key) {
cachedImageSource = imageSource.fromNativeSource(image);
console.log(cachedImageSource)
}
},
error: () => {
console.log('Error')
}
});
}
cache.disableDownload();
return cachedImageSource;
}
}
}
</script>
但是,我的控制台中的输出如下:
iOS:
{ ios: {} }
安卓:
{ android:
{ constructor:
{ [Function]
[length]: 0,
[name]: '',
[arguments]: null,
[caller]: null,
[prototype]: [Object],
createBitmap: [Object],
createScaledBitmap: [Object],
extend: [Object],
CREATOR: [Object],
DENSITY_NONE: 0,
CONTENTS_FILE_DESCRIPTOR: 1,
PARCELABLE_WRITE_RETURN_VALUE: 1,
null: [Circular],
class: [Object],
CompressFormat: [Object],
Config: [Object] } } }
当然总是输出:downloading image, setting it in cache, and getting from cache,从不输出getting image from cache。图片永远不会显示,永远不会保存在缓存中,也永远不会从缓存中获取。
我不知道我做错了什么。
提前致谢。
【问题讨论】:
-
图片是异步下载的,不能直接返回图片。尝试将其设置为数据中的属性,以便在更新数据对象后立即同步图像。如果您仍有问题,请分享 Playground 示例。
-
嘿@Manoj 感谢您的回答!我尝试将其保存在数据对象中,但 ios 仍然没有返回任何内容:play.nativescript.org/?template=play-vue&id=Lft4qB 还有比将 2 个对象保存在数据中更好的方法(在我的情况下是 cachedImages 和 exampleImages?)
-
你仍然对数据对象犯同样的错误,你应该等待异步调用完成。
标签: android ios vue.js nativescript nativescript-vue