我的组件内有图像,但在启动时未显示。当我显示我的组件时,我的图像不会立即显示,而是加载。
我想在根应用程序上预加载图像,以便在组件处于活动状态时立即显示。
你会怎么做?
我有多个图像要加载,我把它们放在一个数组中。
在循环中,我在加载图像时增加一个计数器。
当这个计数器等于我的图像的数组长度时,我想删除加载指示器。
我不知道为什么,那不起作用。
new Vue({
el: "#app",
created() {
let imageLoaded = 0;
for (const imageSrc of this.imagesToPreload) {
if (imageLoaded === this.imagesToPreload.length) {
console.log("Done !");
this.loading = false;
}
const img = new Image();
img.src = imageSrc;
img.onload = () => {
imageLoaded++;
console.log(imageLoaded);
};
}
},
data() {
return {
isLoading: true,
imagesToPreload: [
"https://placeimg.com/1280/800/any",
"https://placeimg.com/1280/800/any",
"https://placeimg.com/1280/800/any"
]
};
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-if="isLoading">Loading...</div>
</div>Run Code Online (Sandbox Code Playgroud)
这是我所做的,我不确定它是否正确:
//store
async addUser({commit}) {
try {
const {data} = await apiService.addUser()
commit('SET_USER', data)
commit('SET_NOTIFICATION', {type:'success', message: 'user successfuly created'})
} catch (error) {
commit('SET_NOTIFICATION', {type:'error', message:error})
}
}
SET_USER(state, user) {
state.users.push(user)
}
Run Code Online (Sandbox Code Playgroud)
//my component:
async addUser() {
this.isLoading = true
await this.$store.dispatch('updatePatient', this.form)
this.isLoading = false
}
Run Code Online (Sandbox Code Playgroud)
合法吗?
有时我认为我的组件中需要更多逻辑,具体取决于成功或拒绝的 api 请求。我应该把所有的逻辑都放在我的行动中吗?就像我现在做的那样?
也许我应该为每个动作添加一个状态状态,例如:
state {
users: []
postUserSuccess: null
postUserError: false
updateUserSuccess: null
updateUserError: false
// ...
}
Run Code Online (Sandbox Code Playgroud)
并使用映射到商店的计算属性在组件中执行我想要的操作?
你怎么认为 ?