当数据api中的图像加载完成时,我正在尝试加载一个函数。但是,该函数似乎在ApiService完成之前就已运行,因此TiffParser.replaceIMG()
函数无法正常工作
这是我的设置:
data: function() {
return {
images: null,
imageLink: apiService.imgSrc,
loading: true,
errored: false
};
},
created: function() {
// fetch the data when the view is created and the data is
// already being observed
apiService
.getImages(this.$route.params.id)
.catch(error => {
console.log(error);
this.errored = true;
})
.then(response => {
this.loading = false;
this.images = response.data;
});
},
//vue js provides us `mounted()`. This means `onload` in javascript
mounted: function() {
TiffParser.replaceIMG();
}
mounted
是此任务的正确生命周期挂钩吗?
答案 0 :(得分:1)
您可以为images
创建一个watcher
。
created() {
const unwatch = this.$watch('images', function(newValue = [], oldValue = []) {
// any code here will execulte once the value of `images` changes
TiffParser.replaceIMG();
unwatch(); // remove the watcher
// Note that you cannot use ES6 arrow functions here, since arrow functions
// are bound to the parent context, and the `this` keyword
// would then not be bound correctly to the Vue instance.
});
// fetch images
}
是否为此任务安装了正确的生命周期挂钩?
是的,如果您需要在初始渲染之前或之后立即访问或修改组件的DOM。
但是,images
在首次安装时将为空,因此使用watcher
代替mounted
钩似乎更适合此用例。