Vue method scroll div to top

后端 未结 5 1059
离开以前
离开以前 2021-01-18 06:20

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 an

5条回答
  •  长情又很酷
    2021-01-18 07:05

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

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

    • 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

       

    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

提交回复
热议问题