【发布时间】:2019-04-09 19:32:14
【问题描述】:
情况:
在一个页面中,有几个组件接收用户列表。收到列表后,会有一个 foreach 循环调用附加组件来获取用户的图像。多个组件可能包含相同的用户,这意味着重复完全相同的 http 请求以获取“重复图像”。为了避免这些不必要的请求,我在 vueX 的 store 中设置了一个用户有某个 base64 图像的信息,这样我就可以验证我是否已经得到了图像。
问题:当第一个组件请求获取图像并将其保存在商店中时,其余组件已经创建,因此商店仍然是空的,我无法检查是否有图片。
解决方案:创建组件时,我通过使用强制商店存在
this.images[this.user.id] = 'reserved';
但是,我不确定这是否是解决这种情况的正确方法。 接受的建议:'D
代码:
父组件
<template>
<div class="info-cards">
<div class="info-users">
<div class="info-label">{{ $t('global.users') }}</div>
<div class="info-images" v-if="users.length > 0">
<base-users-image
v-for="user in users"
:key="user.name"
:user="user"
/>
</div>
<div v-else class="message">{{ $t('global.noUsersRole') }}</div>
</div>
</div>
</template>
<script>
// import components
const baseUsersImage = () => System.import(/* webpackChunkName: 'usersImage' */ './../../users/baseUsersImage');
export default {
props: {
users: Array,
packages: Array
},
components: {
baseUsersImage: baseUsersImage
},
}
</script>
图像组件
<template>
<router-link to="user" class="anchor-image">
<img v-if="show" :src="image" :alt="user.name" class="image">
<div v-else class="image-default">t</div>
</router-link>
</template>
<script>
// import requests
import requests from './../../../helpers/requests.js';
// import store
import { mapGetters, mapActions } from 'vuex';
export default {
props: {
user: Object
},
data() {
return {
image: '',
show: false
}
},
created() {
if (this.user.avatar) { // check if user has avatar
if ( this.images[this.user.id] == null) { // check if it already exists in the store
this.images[this.user.id] = 'reserved'; // set as reserved in store
requests.get(this.user.avatar, { responseType: 'arraybuffer' }) // faz o pedido a API da image
.then( (response) => {
this.saveImage( { id: this.user.id, url: `data:${response.headers['content-type']};base64,${Buffer.from(response.data, 'binary').toString('base64')}` } );
}, error => {
console.log(error);
});
}
}
},
methods: {
...mapActions({
saveImage: 'saveImage'
})
},
computed: {
...mapGetters({
images: 'images'
})
},
watch: {
images: {
immediate: true,
deep: true, // so it detects changes to properties only
handler(newVal, oldVal) {
if ( newVal[this.user.id] !=='reserved'
&& this.user.avatar
&& newVal[this.user.id] !== undefined
) {
this.image = newVal[this.user.id];
this.show = true;
}
}
}
}
}
</script>
商店
const state = {
images: {}
}
const SAVE_IMAGE = (state, payload) => {
state.images = {
...state.images,
[payload.id] : payload.url
}
}
const saveImage = ({commit}, payload) => {
commit('SAVE_IMAGE', payload);
}
【问题讨论】:
标签: image vue.js axios vue-component vuex