[英]Vue.js not rendering elements in a list
因此,對於上下文,我有一個應用程序的客戶端,其中服務器通過套接字連接向客戶端發送客戶端的朋友。 我可以檢索朋友,甚至創建可點擊的列表元素,以便用戶可以向朋友發送消息等。但是,我遇到的一個問題是,當使用 mustache 語法來呈現信息時,什么都不呈現。 我有以下代碼。
index.html(以下在app div里面)
<div id="friends">
<p>Friends</p>
<ul id="friend-list">
<li
v-for="friend in friends"
v-on:click="setFriend(friend.id)"
>Friend:{{friend.text}}
</li>
</ul>
</div>
索引.js
var socket = io.connect('http://localhost:3000');
var app = new Vue({
el: '#app',
data: {
messageContent: '',
friends: [],
messages: []
}
})
socket.on('connect', function(){
socket.emit('authentication', Cookies.get('user'));
socket.on('authenticated', function() {
socket.on('sendFriends',(data) => {
data.forEach(element => {
console.log(element.username)
app.friends.push({
text: element.username + '.'+element.id,
id: element.id
})
})
toUser = app.friends[0].id
})
})
})
即使我在沒有來自套接字連接的數據的情況下填充朋友數組,每個元素上的文本也不會呈現。 我的意思是,會有具有點擊功能的項目符號,但沒有文本。 但是,當我創建 codepen 時,數據會正確呈現。 這是否與套接字連接以及 Vue 對數據更改的反應有關? https://codepen.io/dvub/pen/XWaebyb(codepen鏈接)
由於 API 調用是異步的,在處理調用和接收數據之前,Vue 已經在讀取friends
的值。 因此,在 API 返回任何內容之前,Vue 已經開始循環訪問friends
數組。
單個friend
作為道具傳遞給子組件。 子組件現在正在尋找該對象的屬性(即, friend.name
)。
但是當組件第一次掛載時,friends 數組是空的。 因此需要添加一個簡單的v-if
來停止渲染,直到您收到信息。
<ul id="friend-list" v-if="friends.length">
您可能還想刪除
toUser = app.friends[0].id
它看起來不像有效的 JS 語法( toUser
在哪里聲明?)。
除非您進入 Vue 的應用程序上下文,否則您無法正確設置friends
值。 所以你應該開始把所有的東西放回你的 Vue 應用程序中。 它應該看起來更像一些東西(我不能保證它可以工作,因為我不知道你的套接字庫是如何工作的,但它應該是這樣構造的):
<div id="friends">
<p>Friends</p>
<ul id="friend-list">
<li v-for="friend in friends"
v-on:click="setFriend(friend.id)">Friend:{{friend.text}}
</li>
</ul>
</div>
const app = new Vue({
el: '#app',
data: {
socket: null,
messageContent: '',
friends: [],
messages: []
},
mounted: {
// Here it depends on how the library works. You may have to use async / await on connection init :
this socket = io.connect('http://localhost:3000');
this.socket.on('connect', function(){
this.socket.emit('authentication', Cookies.get('user'));
this.socket.on('authenticated', function() {
this.socket.on('sendFriends',(data) => {
data.forEach(element => {
console.log(element.username)
this.friends.push({
text: element.username + '.'+element.id,
id: element.id
});
});
});
// I don't know what you're trying to do here so I commented this one :
// toUser = app.friends[0].id
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.