I am trying to add the corresponding avatar to each notification, so I can display it along with the rest of notification, but I can't figure this out on my own. Here's the HTML inside the Vue.js template:
<li class="notification" v-for="(notification, index) in notifications">
<a>
<span class="image">
<img :src="notification.avatar" alt="Avatar" />
</span>
<span class="link">
<span v-text="notification.data.sender_name"></span>
</span>
<span class="message" v-text="notification.data.message"></span>
</a>
</li>
And here's the js:
data() {
return {
user: this.initialUser,
notifications: this.initialUser.unread_notifications,
}
},
created() {
let self = this;
self.notifications = this.initialUser.unread_notifications;
self.notifications.forEach(function(notification) {
if(notification.data.sender_id) {
axios.post(self.user.path + '/get-avatars', {
id: notification.id,
}).then((response) => {
let promise = new Promise(function (resolve, reject){
notification.avatar = response.data;
});
});
}
});
},
The problem that I'm having is that the v-for
runs before the created()
method, so that my notifications object does not have the avatar property at the time the v-for is performed.
Is there any way I could run the v-for only after the created() has been completed?
Thank you!
Use
this.$set(notification, 'avatar', response.data)
to trigger reactivity manually. You need to have an avatar
property beforehand in order to automatically have reactivity when doing notification.avatar = ...
. If you dont have the property, you need to use this helper function from Vue.
This can be a problem with objects as well as arrays.
For more info see https://v2.vuejs.org/v2/guide/reactivity.html