Javascript Vue方法将div滚动到顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45658042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:08:38  来源:igfitidea点击:

Vue method scroll div to top

javascriptvuejs2

提问by TheRealPapa

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?

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

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

My vuemethod:

我的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);
            });

        }
    }

回答by Vamsi Krishna

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

这是由于 vue 异步更新 dom 的方式造成的。深入了解Reacivity(异步更新队列)

  • To reflect changes immediately use vm.$nextTick(callback)

  • instead of querying the dom element using document.getElementById()I recommend add a refattribute to your toolbar-chatelement and reference it in your method using this.$refs. See docsfor more on refattribute

     <div id="toolbar-chat" ref="toolbarChat"></div>
    
  • 要立即反映更改,请使用 vm.$nextTick(callback)

  • document.getElementById()我建议不要使用查询 dom 元素,而是ref向您的toolbar-chat元素添加一个属性,并在您的方法中使用this.$refs. 有关属性的更多信息,请参阅文档ref

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

So you method should be

所以你的方法应该是

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);
        });

    }
}

Here is the working fiddle

这是工作小提琴

回答by Ognyan Dimitrov

Here is my solution :

这是我的解决方案:

One global div in main container

主容器中的一个全局 div

<div id="topDiv"></div>

One global function put in the Vue prototype :

Vue 原型中的一个全局函数:

Vue.prototype.$scrollTop = function () {
  var element = document.getElementById("topDiv");
  var top = element.offsetTop;
  window.scrollTo(0, top);
}

The same anchor everywhere :

到处都是同一个锚:

<a @click="$scrollTop">Go to the top</a>