I am trying to build a simple chat app with Vue.js. My problem is that the message area needs to scroll to the bottom when a new message is written.
I looping through the messages with v-for directive. Is there an event when v-for has updated the DOM?
I have made it so that the message area div listens to component's message-array. I tried so that in the same function that I am appending the message to the array, it would set the message area div's scrollTop to 99999. But the problem is that v-for is not done updating the DOM, so it will not scroll to the correct point.
v-if. The directive v-if is used to conditionally render a block. The block will only be rendered if the directive's expression returns a truthy value.
Emitting Events with setup()$emit() to send our event. Instead, we can access our emit method by using the second argument of our setup function – context . context has access to your components slots, attributes, and most importantly for us, its emit method. We can call context.
The v-show directive is a Vue. js directive used to toggle the display CSS property of a element with our data via inline styles. If the data is true it will make it visible else it will make it invisible.
v-if - Only renders the element to the DOM if the expression passes. v-show - Renders all elements to the DOM and then uses the CSS display property to hide elements if the expression fails.
I had a similar issue but I took a different approach using the vue.nextTick()
. I needed to be sure the v-for
had finished rendering as the component will not re-render immediately, It will update on the next “tick” when the queue is empty.
Vue.component('message', { data() { return { message: [] } }, methods: { updateMessageArray(newMessage) { this.message.push(newMessage); this.$nextTick(() => { // Scroll Down }) } } })
https://vuejs.org/v2/api/#Vue-nextTick
https://vuejs.org/v2/guide/reactivity.html#Async-Update-Queue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With