简体   繁体   中英

VueJS data return array not reactive with template

I'm making a chat system for admin and clients using VueJS and socket.io. When a client connects to the server and entered a name, it should add a new row in the admin chats with the client's name. And when they disconnect it should be removed from the list of admin chats. But that doesn't work. I have to force reload the page then the chat is gone.

Template:

    <div class="chats" id="chat"  v-if="chats.length >= 1">
        <div class="chat" v-for="chat in chats">
            <b>{{ chat.clientName }}</b>
            <p>ID: {{ chat.clientID }}</p>
            <div class="jens-button">
                <img src="/icons/chat-bubble.svg">
            </div>
        </div>
    </div>
    <div class="chats" v-else>
        <div class="chat">
            <b>There are no chats avaiable.</b>
        </div>
    </div>

data:

        data() {
            return {
                chats: [],
            }
        },


        method() {                                           
            socket.on('update clients', (clients) => {
                console.log(clients);
                this.chats = [];
                if(clients.length >= 1) {
                    this.chats = clients;
                } else {
                    this.chats = [];
                }
            });
        }

What goes wrong? If someone finds the answer, can you also give me an explanation why it isn't working? Thank you!

The way you got it right now is not a valid way to declare methods in Vue. This way your socket.on never gets declared. Please make use of mounted() . You can read more about the lifecycles of components here .

A barebones example would be the following. Also make sure to add a :key to your v-for .

<div class="chats" id="chat"  v-if="chats.length >= 1">
        <div class="chat" v-for="chat in chats" :key="chat.clientID">
data() {
  return {
    chats: [],
  }
},
mounted() {
  socket.on('update clients', (clients) => {
    // You could also declare a dedicated method for this instead of doing it inline
    console.log(clients);
    if(clients.length >= 1) {
      this.chats = clients;
    } else {
      this.chats = [];
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM