因此,對于背景關系,我有一個應用程式的客戶端,其中服務器通過套接字連接向客戶端發送客戶端的朋友。我可以檢索的朋友,甚至創建可點擊串列中的元素,使用戶可以將訊息發送給朋友,等等。然而,有一個問題,我有是用胡子語法來呈現資訊時,沒有渲染。我有以下代碼。
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鏈接)
uj5u.com熱心網友回復:
friends除非您進入 Vue 的應用程式背景關系,否則您無法正確設定值。所以你應該開始把所有的東西放回你的 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
});
}
});
uj5u.com熱心網友回復:
由于 API 呼叫是異步的,Vuefriends在處理呼叫和接收資料之前已經讀取了 的值。因此friends,在 API 回傳任何內容之前,Vue 已經開始遍歷陣列。
個體friend作為道具傳遞給子組件。子組件現在正在尋找該物件的屬性(即,friend.name)。
但是當組件第一次掛載時,friends 陣列是空的。因此需要添加一個簡單v-if的停止渲染直到您收到資訊。
<ul id="friend-list" v-if="friends.length" :key="friends.name">
您可能還想洗掉
toUser = app.friends[0].id
它看起來不像有效的 JS 語法(在哪里toUser宣告?)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344824.html
標籤:javascript html Vue.js
下一篇:Vuex狀態未設定為getter
