Vue方法滚动div到顶部 [英] Vue method scroll div to top

查看:112
本文介绍了Vue方法滚动div到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 vue .我有以下方法,可以使用 id ="toolbar-chat" 将聊天消息添加到div中.这个div允许在y轴上滚动,我希望每次添加新消息时div跳到顶部.为什么我的JS无法正常工作?

I am learning vue. I have the following method where I add a chat message to a div with id="toolbar-chat". This div allows scrolling on y axis and I would like the div to jump to the top every time a new message is added. Why is my JS not working?

    document.getElementById("toolbar-chat").scrollTop = 0;

我的 vue 方法:

    methods: {
        addMessage(message) {
            this.messages.unshift(message);

            document.getElementById("toolbar-chat").scrollTop = 0;

            axios.post(chat_send_route, message)
            .then(response => {
                console.log(response.data);
            });

        }
    }

推荐答案

之所以发生这种情况,是因为vue异步更新了dom.参见深度响应(异步更新队列)

This is happening due to way vue updates the dom asynchronously. See Reacivity in depth(Async update Queue)

  • 要立即反映更改,请使用 vm.$ nextTick(callback)

而不是使用 document.getElementById()查询dom元素,我建议在 toolbar-chat 中添加 ref 属性元素,并在您的方法中使用 this.$ refs 对其进行引用.有关 ref 属性

instead of querying the dom element using document.getElementById() I recommend add a ref attribute to your toolbar-chat element and reference it in your method using this.$refs. See docs for more on ref attribute

 <div id="toolbar-chat" ref="toolbarChat"></div>

所以您的方法应该是

methods: {
    addMessage(message) {
        this.messages.unshift(message);
        this.$nextTick(() => {
            this.$refs.toolbarChat.scrollTop = 0;
        });

        axios.post(chat_send_route, message)
        .then(response => {
            console.log(response.data);
        });

    }
}

这是工作中的小提琴

这篇关于Vue方法滚动div到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆