vue 实现聊天框滚动到底
在需要出现滚动条的 DOM上添加 v-scroll 属性:
<div class="chat-box" v-scroll="{auto: true}"> <div class="dialog-box"> <div class='' v-for="item in msgList" :key="item"> <div v-html="item.content"></div> </div> </div> </div>
编写自定义指令 scroll
<script> export default { ... directives: { scroll: { bind (el, binding, vnode) { const pause = (e) => { let auto = binding.value ? binding.value.auto : false let scrolled = el.scrollTop + el.clientHeight + 1 < el.scrollHeight let timeout window.clearTimeout(timeout) timeout = setTimeout(() => { if (auto && scrolled) { el.setAttribute('v-scroll2-manually', 'yes') } else if (auto && !scrolled) { el.setAttribute('v-scroll2-manually', '') } else { el.removeEventListener('scroll', pause) } }, 600) } el.addEventListener('scroll', pause) }, update (el, binding, vnode) { if (!el.getAttribute('v-scroll2-manually')) { vnode.context.$nextTick(() => { el.scrollTop = el.scrollHeight - el.clientHeight }) } } } } ... } </script>