目 录CONTENT

文章目录

Ansi-up使用记录

cplinux98
2022-08-30 / 0 评论 / 0 点赞 / 611 阅读 / 365 字 / 正在检测是否收录...

00:文章简介

记录一下vue中ansi_up的使用

01:ansi_up介绍

官方站点 https://github.com/drudru/ansi_up

这是一款可以让ansi编码中的颜色字符转换为html中的颜色标签,从而实现带有颜色的命令行输出等等

02:在vue项目中使用

npm install ansi_up
<template>
  <div class="console">
    <div class="output" id="output" v-for="(output, index) in outputList" :key="index">
      <p v-html="output"></p>
      <!-- element 中使用 v-html 用来渲染html标签 -->
    </div>
</template>

<script>
import AnsiUp from 'ansi_up'
import { Loading } from 'element-ui'

export default {
  data() {
    return {
      outputList: [],
    }
  },
  methods: {
    submitCommand() {
      const name = 'command'
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          // element-ui loading组件,运行命令时有个加载动画
          const loadingInstance = Loading.service({
            lock: true,
            text: '运行中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.8)',
            target: document.querySelector('.el-dialog__body')
          })
          const { data: response } = await this.$http.post(`api`, this.commandForm)
          if (response.code) {
            this.$nextTick(() => {
              loadingInstance.close()
            })
            return this.$message.error(response.message)
          }
          this.$message.success('命令提交成功')
          // ansi_up处理
          const ansiUp = new AnsiUp()
          const outputs = response
          const html = ansiUp.ansi_to_html(outputs)
          // 处理结束得到html
          this.outputList.push(html)
          this.$nextTick(() => {
            loadingInstance.close()
          })
        } else {
          this.$message.error('验证失败,请检查内容!')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.console {
  width: 100%;
  height: 300px;
  background-color: #000;
  font-size: 15px;
  padding: 5px;
  color: #fff;
  white-space: pre-line;
}
</style>

0

评论区