近期有一个功能优化需求,物联网设备在跟服务器自动化调试通信的过程中,在网页的控制台上需要时时显示出物联网设备的回复信息,网页控制台跟服务器使用的websocket的方式来时刻保持长链接。网页控制台设计了一个div,设置样式为固定高度,超过高度的显示滚动条。但是目前无法看到最底部的调试返回信息,需要在服务器回复时自动把滚动条返回底部。跟网页聊天的界面功能一样。

原理:我们通过div的scrollTop方法来完成。

代码:


<template>
<div>
<el-row class="console-result" id="consoleResultContainer">
	<div v-html="runResult"></div>
</el-row>
</div>
</template>
<script>
export default {
  name: 'DeviceConsole',
  data(){
    return {
	  runResult: ''
	}
  },
  methods: {
    websocketonmessage(e){
      //console.log("数据接收")
      //console.log(e)
      //const redata = JSON.parse(e.data)
      this.runResult = this.runResult + e.data + "<br/>"
      let container = this.$el.querySelector("#consoleResultContainer")
      container.scrollTop = container.scrollHeight
    },
  }
}
</script>
<style scoped>
.console-result {
  height: 500px;
  border: 1px solid #dfe4ed;
  background: #eeeeee;
  overflow: auto;
}
</style>