<ul ref="contRef" class="list"> <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li> </ul> <button @click="sendMessage">Send</button> import { ref, reactive, nextTick } from 'vue'; export default { setup() { const contRef = ref(null); // 使用 ref 引用 list 的 DOM 元素 const state = reactive({ messages: [], }); const sendMessage = () => { // 使用 nextTick 等待 DOM 更新后再进行滚动操作 nextTick(() => { contRef.value.scrollTop = contRef.value.scrollHeight; }); } return { contRef, state, sendMessage, }; } }
vue3 点击按钮使内容区滚动到底部
于 2023-04-24 13:21:17 首次发布
该代码段展示了如何在Vue.js应用中创建一个消息列表,并在发送新消息后自动将滚动条移动到底部。它利用`ref`来获取DOM元素,`reactive`创建响应式状态,并用`nextTick`确保在DOM更新后执行滚动操作。

2749

被折叠的 条评论
为什么被折叠?



