2017-08-13 143 views
0

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

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

     } 
    } 

回答

1

这是发生由于方式VUE异步更新DOM。见Reacivity in depth(Async update Queue)

  • 为了反映变化立即使用vm.$nextTick(callback)

  • 而不是使用document.getElementById()查询的DOM元素的我建议加一个ref属性您toolbar-chat元素,并使用this.$refs引用它在你的方法。更多关于ref属性见docs

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

    } 
} 

这里是工作fiddle