xterm js 使用方法(包括 选中复制 与 右键粘贴)
不废话直接上代码
<template>
<div :id="id" class="xterm" @click.right="pastVal()">
<q-resize-observer @resize="onCiLogPanelResize"/>
</div>
</template>
<script>
import {defineComponent} from 'vue';
import '@xterm/xterm/css/xterm.css'
import { Terminal } from '@xterm/xterm';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { FitAddon } from '@xterm/addon-fit'
import { AttachAddon } from '@xterm/addon-attach'
export default defineComponent({
name: 'SunTerminal',
components: {},
props:{
id:{
type: String
},
link: {
type: String,
}
},
data () {
return {
socket: null,
terminalElement: null,
fitAddon: null,
attachAddon: null,
rows: 24,
copy: ''
}
},
methods: {
initSocket () {
this.socket = new WebSocket(this.link)
// 连接成功后
this.socket.onopen = () => {
this.initTerminal()
}
this.socket.onerror = (err) => {
}
this.socket.onclose = (err) => {
this.socket.close();
console.log("关闭 socket");
}
},
// 初始化 Terminal
initTerminal () {
this.terminalElement = new Terminal()
this.terminalElement.open(document.getElementById(this.id))
this.fitAddon = new FitAddon();
this.terminalElement.loadAddon(this.fitAddon);
this.attachAddon = new AttachAddon(this.socket)
this.terminalElement.loadAddon(this.attachAddon);
this.fitAddon.fit()
this.terminalElement.onSelectionChange( () => {
if (this.terminalElement.hasSelection()) {
this.copy = this.terminalElement.getSelection();
navigator.clipboard.writeText(this.copy)
}
});
},
onCiLogPanelResize(size){
this.resizeScreen(size)
},
// 内容全屏显示
resizeScreen (size) {
try {
this.fitAddon.fit() // fit时已经改变了terminalElement的宽度
// 窗口大小改变时触发xterm的resize方法,向后端发送行列数,格式由后端决定
// 这里不使用size默认参数,因为改变窗口大小只会改变size中的列数而不能改变行数,所以这里不使用size.clos,而直接使用获取我们根据窗口大小计算出来的行列数
this.terminalElement.resize(parseInt(this.terminalElement.cols),parseInt(this.rows))
} catch (e) {
console.log('e', e.message)
}
},
pastVal(){
navigator.clipboard.readText().then(data=>{
this.terminalElement.paste(data)
});
}
},
mounted() {
this.initSocket();
document.addEventListener('contextmenu',function(e){
e.preventDefault();
})
},
beforeUnmount() {
this.socket.close()
console.log("beforeUnmount")
}
});
</script>
<style scoped>
.xterm ::-webkit-scrollbar {
width:8px;
height:8px;
border-radius:10px;
background-color:#F5F5F5;
}
.xterm ::-webkit-scrollbar-track
{
-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.3);
border-radius:10px;
background-color: #F5F5F5;
}
.xterm ::-webkit-scrollbar-thumb
{
border-radius:10px;
-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,.3);
background-color: #447aff;
}
</style>