single-contact
我有一个包含如下组件的主页:
<el-row id="rowContact">
<!-- Contacts -->
<el-scrollbar wrap-class="list" :native="false">
<single-contact ref="singleContact"></single-contact>
</el-scrollbar>
</el-row>
我想在 AJAX 轮询之后动态呈现这个组件,所以SingleContact.vue
我使用$axios
并mounted()
从后端请求数据。我想使用v-for
. 我有我的代码:
<template>
<div :key="componentKey">
<el-row id="card" v-for="contact in contacts" :key="contact.convUsername">
<div id="avatar" ><el-avatar icon="el-icon-user-solid"></el-avatar></div>
<h5 id='name' v-if="contact">{{contact.convUsername}}</h5>
<div id='btnDel'><el-button size="medium" type="danger" icon="el-icon-delete" v-on:click="delContact(contact.convUsername)"></el-button></div>
</el-row>
</div>
</template>
数据结构为:
data() {
return {
timer: null,
contacts: []
}
而Ajax轮询的方法是:
loadContacts () {
var _this = this
console.log('loading contacts')
console.log(localStorage.getItem('username'))
this.$axios.post('/msglist',{
ownerUsername: localStorage.getItem('username')
}).then(resp => {
console.log('success')
var json = JSON.stringify(resp.data);
_this.contacts = JSON.parse(json);
console.log(json);
console.log(_this.contacts[0].convUserName);
// }
}).catch(failResponse => {
console.log(failResponse)
})
}
这是我在控制台中得到的: 控制台结果 我计算的挂载方法如下:
beforeMount() {
var self = this
this.$axios.post('/msglist',{
ownerUsername: localStorage.getItem('username')
}).then(resp => {
this.$nextTick(() => {
self.contacts = resp.data
})
}).catch(failResponse => {
console.log(failResponse)
})
},
mounted() {
this.timer = setInterval(this.loadContacts(), 1000)
this.$nextTick(function () {
this.loadContacts()
})
},
beforeDestroy() {
clearInterval(this.timer)
this.timer = null
}
我可以在控制台中获得正确的数据。看来后端可以正确的向前端发送json,前端也能收到正确的结果。但是页面并没有按预期呈现。
任何建议都会很棒!先感谢您!