vanilla javascript scroll method doesn't work in component
Version
3.2.20
Reproduction link
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 ?
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>
I added const box1 = ref(null)
and still get the same result, here
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>
According to the offical doc, nextTick
is a global api method, why do I still have to do the import if it is global ?
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