Javascript 创建()完成后是否可以运行v-for?
我正在尝试将对应的化身添加到每个通知中,这样我就可以将其与通知的其余部分一起显示,但我自己无法解决这个问题。以下是Vue.js模板中的HTML:Javascript 创建()完成后是否可以运行v-for?,javascript,vue.js,axios,es6-promise,Javascript,Vue.js,Axios,Es6 Promise,我正在尝试将对应的化身添加到每个通知中,这样我就可以将其与通知的其余部分一起显示,但我自己无法解决这个问题。以下是Vue.js模板中的HTML: <li class="notification" v-for="(notification, index) in notifications"> <a> <span class="image"> <img :src="notific
<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>
我遇到的问题是v-for
在created()
方法之前运行,因此在执行v-for时,我的通知对象没有avatar属性
是否只有在创建()完成后才能运行v-for
谢谢大家! 除非我这里遗漏了什么,否则没有理由延迟执行
v-for
指令。您需要做的就是确保通知
对象已经设置了化身
字段,即使它被设置为未定义
。您可以从父对象或使用克隆传入对象的计算属性执行此操作,该属性集为:this.initialUser.unread\u notifications.map(notification=>Object.assign({avatar:undefined},notification)
如果您不希望在加载化身之前呈现通知,您可以:
v-if=“!!notification.avatar”
添加到li
元素中。(标准Vue linter会建议不要这样做;我碰巧认为这非常方便。它基本上会根据条件过滤输出。)unread\u notifications\u with\u avatars
,它等于(例如this.initialUsers.unread\u notifications.filter(notification=>!!notification.avatar)
,并在v-for
指令中使用它Promise.all(…)。然后(()=>this.showTheList=true)
)。虽然这有点棘手,但在我看来,在这种情况下您并不是真的需要它。使用
this.$set(通知,'avatar',响应.数据)
手动触发反应。您需要事先拥有化身
属性,以便在执行通知时自动具有反应。化身=…
。如果您没有该属性,则需要使用Vue的此帮助功能
这可能是对象以及数组的问题
有关更多信息,请参见。$set(通知,'avatar',response.data)将触发反应,这非常棒,而且很有效!实际上是
self。$set(通知,'avatar',response.data)
但无论如何,你还是做对了!你可以将此添加为解决方案,让其他人也能看到,我会将其标记为正确答案。万分感谢!干杯!
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;
});
});
}
});
},