Subscribe on changes!

vanilla javascript scroll method doesn't work in component

avatar
Oct 12th 2021

Version

3.2.20

Reproduction link

sfc.vuejs.org/

Steps to reproduce

click 'add message' button

What is expected?

message is added to the box and scroll to the bottom where the "..." is visible

What is actually happening?

message is added but no scrolling


In the SFC playground, the result only takes up about 25% of the viewport height, is that normal ?

avatar
Oct 12th 2021

You need to expose the box1 variable

<script setup>
import { ref, nextTick } from 'vue'

const msg = ref('Hello World!')
const box1 = ref(null)         //    <------- Look here. 
const messages = ref([
        { body: "Message 1" },
        { body: "Message 2" },
        { body: "Message 3" },
        { body: "Message 4" },
        { body: "Message 5" }
      ])
const addMessage1 = async function (){
      messages.value.push({ body: `Message ${messages.value.length+1}`})

      await nextTick();

     box1.value.scrollTop = box1.value.scrollHeight;
}
</script>
avatar
Oct 12th 2021

I added const box1 = ref(null) and still get the same result, here

avatar
Oct 12th 2021

I added const box1 = ref(null) and still get the same result, here

You also need to import nextTick from 'vue'

<script setup>
import { ref, nextTick } from 'vue'    //    <------- Look here. 

const msg = ref('Hello World!')
const box1 = ref(null)         //    <------- Look here. 
const messages = ref([
        { body: "Message 1" },
        { body: "Message 2" },
        { body: "Message 3" },
        { body: "Message 4" },
        { body: "Message 5" }
      ])
const addMessage1 = async function (){
      messages.value.push({ body: `Message ${messages.value.length+1}`})

      await nextTick();

     box1.value.scrollTop = box1.value.scrollHeight;
}
</script>
avatar
Oct 12th 2021

According to the offical doc, nextTick is a global api method, why do I still have to do the import if it is global ?

avatar
Oct 12th 2021

According to the offical doc, nextTick is a global api method, why do I still have to do the import if it is global ?

You may have misunderstood the meaning of the global API.Global API