div cann't scroll to bottom on mounted vueJs

Viewed 26

I have a chat template where I want scrolling the div that contain messages to the bottom when I open the discussion
but it doesn't work on mounted the component, it workd just when I send message, despite I call the function in mounted hook
Any suggestion to resolve it ?
this is my component :

<script>
// import section    
export default {
  components : {
  //...
  },
  props: {
    contact: {
      type: Object,
      default: {},
    },
    messages: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      auth : null,
      newMessage : {
        message: "",
        from_id: null,
      },
      container : null
    }
  },
  created() {
    this.auth = usePage().props.value.auth.user
  },
  mounted() {
    this.lastMessages()
    this.getMessages()
  },

  methods: {
    async sendMessage(message) {
      if (message == "") return;

      this.newMessage = {
        ...this.newMessage,
        message: message,
        to_id: this.contact.id,
        from_id : this.auth.id
      };
      //Pushes it to the messages array
      this.messages.push(this.newMessage);
      this.$nextTick(() => {
        this.lastMessages()
      })
...        
    },
    getMessages() {
     ....
    },
    lastMessages () {
      this.container = this.$refs.messages
      this.container.scrollTop = this.container.scrollHeight
    }
  }
}
</script>
<template>
  <div  class="flex-1 p:2 sm:p-6 justify-between flex flex-col">
    <div clas="...."   >
      <HeaderChat :contact="contact" />      
    </div>
    <div ref="messages" class="..."    >
      <ChatMessage :messages="messages" :contact="contact" :auth="auth" />
    </div>    
    <InputBloc @send-message="sendMessage" :contact="contact">
      <slot />
    </InputBloc>
  </div>
</template>
1 Answers

Try this solution in the mounted :

  this.$refs.messages.scrollIntoView({ behavior: "smooth" });

a second solution is to add dynamic refs when you make your messages loop inside the component ChatMessage example :

ChatMessageComponent :

<div v-for="(val, index) in messages" :key="index">
    <div :ref="'chat' + index" >{{chat}}</div>
</div>

OtherComponent :

   this.$refs["chat" + this.messages.length].scrollIntoView({ behavior: "smooth" });
Related