[Vuejs]-VueJS array not updating

1👍

Vue allows for the page elements to react to variable changes rather than explicitly modifying the DOM with getElementById / createElement / appendChild.

Similar to how you are managing the display of users, use Vue data for an array of messages and a string for the label text.

<template>
  <div id="left_container" ref="usersContainer">
    <button v-for="user in users" :key="user.userID" >{{ user.username }}</button>
  </div>
  <div id="right_container">
    <ul id="messages">
      <!-- using the array index as a key is not recommended, but 
           will work for simple array appending -->
      <li v-for="(message, index) of messages" :key="index">
        {{ message.msg }}
      </li>
    </ul>
    <div id="bottom_container">
    <label id="lt">
      {{ lbl_writing }}
    </label>
    <form id="form" @submit.prevent="onSubmit" action="">
      <input id="input" v-model="in_msg" autocomplete="off" v-on:input="vChanged"/><button>Send</button>
    </form>
  </div>
  </div>
</template>

Then the script just needs to modify the messages and lbl_writing variables, rather than modifying the elements directly

<script>
  import socket from "../socket"
 
  export default {
    name: "MyChat",
    data() {
      return {
        in_msg:'',
        users: [],
        selectedUser: null,
        messages: [],
        lbl_writing: null,
      };
    },
    mounted()
    {
      socket.on('chat mess', function(msg) {
        this.messages.push({ msg })
      });
      socket.on("private message", ({ content, from }) => {
        var msg = from + " : " + content;
        this.messages.push({ content, from, msg })
      });
      socket.on('chat message not', function(msg) {
        this.lbl_writing = msg
      });
      socket.on('users',function(users){
        this.users = [...users];
        console.log(this.users);
      });
      socket.on('user connected',function(user)
      {
        this.users.push(user);
      })
    }
   
  };
</script>

👤Matt

Leave a comment