先看样式:
1、安装依赖包,注意版本:
2、代码部分:
<template>
<div>
<div id="xterm" class="xterm"/>
</div>
</template>
<script>
import {Terminal} from 'xterm'
import {FitAddon} from 'xterm-addon-fit'
import {AttachAddon} from 'xterm-addon-attach'
let socket = null;
export default {
name: "RttyImplement",
props: {
},
data() {
return {
id: ''
}
},
computed: {
url(){
return 'ws://'+window.location.host + '/api/v1/ws?dev_id='+this.id;
}
},
mounted() {
this.id = this.$route.query.id;
this.initSocket()
},
beforeDestroy() {
socket.close()
// this.term.dispose()
},
methods: {
initTerm() {
const term = new Terminal({
allowProposedApi: true,
fontSize: 14,
cursorBlink: true,
disableStdin: false,
LogLevel: 'debug'
})
term.open(document.getElementById('xterm'))
const attachAddon = new AttachAddon(socket)
const fitAddon = new FitAddon()
term.loadAddon(attachAddon)
term.loadAddon(fitAddon)
fitAddon.fit()
term.focus()
this.term = term
},
initSocket() {
socket = new WebSocket(this.url);
console.log(socket)
this.socketOnClose()
this.socketOnOpen()
this.socketOnError()
},
socketOnOpen() {
socket.onopen = () => {
// 链接成功后
console.log("--------------open socket-------------")
this.initTerm()
}
},
socketOnClose() {
socket.onclose = () => {
console.log('close socket')
this.$router.push({path: '/'})
}
},
socketOnError() {
socket.onerror = () => {
console.log('socket 链接失败')
}
}
}
}
</script>
<style scoped>
.xterm {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
</style>
通过websocket建立连接