【发布时间】:2018-12-22 23:56:58
【问题描述】:
假设我有两个 Vue 文件,A.vue 和 B.vue。在 A 内部有一个指向 B 的路由器链接,其中包含我从 Firebase 实时数据库下载的大量图像。每次我从 A 导航到 B 时,图像的加载速度都没有达到我需要的速度,因此我需要一种方法在 A.vue 中预加载这些图像,以便在单击链接时将它们全部呈现在 B.vue 中.
到目前为止,我所做的是在 A.vue 上的 mounted() 挂钩中使用方法 getUrls() 来获取图像的下载 url 并将它们存储在 localStorage 上,而那时我已经到了 B.vue,B 中的 mounted() 钩子触发了 setImage() 方法,该方法使用 callback 函数作为参数。
我已经阅读了有关 router.BeforeEach() 导航守卫方法的信息,但我真的不知道如何实现它,也不确定这是否能解决我的问题。
我的代码:
A.vue
<template>
<div>
</div>
</template>
<script>
export default {
methods:{
getUrls: function(path, localStorage_id){
var storage = Firebase.storage();
var storageRef = storage.ref();
var pathReference = storageRef.child(path);
pathReference.getDownloadURL().then(function(url) {
let localStorageId = localStorage_id;
localStorage.setItem( localStorageId, url);
}).catch(function(error) {
});
}
},
mounted(){
this.getUrls("path/to/img", "img_id"); // this Is just for one image
(to keep it simple)
},
}
</script>
B.vue
<template>
<div>
<img id="img_id">
</div>
</template>
<script>
export default {
methods:{
setImage: function(localStorageId, imgId, setSrc){
var imgURL = localStorage.getItem(localStorageId);
console.log(imgURL);
setSrc(imgId, imgURL);
},
// callback function
setSrc: function(imgId, imgURL){
var img = document.getElementById(imgId);
img.src = imgURL;
}
},
mounted(){
this.setImage("localStorage_id", "img_id", this.setSrc);
},
}
</script>
(为简单起见省略了style标签)
我希望无需等待(太久)就可以观看所有图像,但我尝试过的操作并没有加快速度。有什么建议吗?
【问题讨论】:
-
我是在路由器里做的,你可以在这里看到我的答案:stackoverflow.com/a/59419841/2045817
标签: javascript asynchronous vue.js preload