文件导入以及在线编辑-xml案例

 

 

<el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xml"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xml格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


 
const { proxy } = getCurrentInstance(); 
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层(用户导入)
  open: false,
  // 弹出层标题(用户导入)
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "地址"
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].clearFiles();
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm () {
  proxy.$refs["uploadRef"].submit();
};

在线编辑器

参考 http://t.csdn.cn/uSgnf

 

// 代码高亮
npm install brace -S
// 剪贴板
npm install vue-clipboard2 -S
// 编辑器
npm install vkbeautify --save

在components下创建一个文件 叫 editor

然后 在下面创建一个js文件 叫 data_format_utils

data_format_utils.js 参考代码如下 用来格式化

vkBeautify - javascript plugin


// 对json和xml进行格式化
import vkbeautify from 'vkbeautify'

export function string_to_json_wrap(v) {
  try {
    if (is_json(v)) {
      return unicode_to_china(JSON.stringify(string_to_json(v), null, '\t'))
    } else {
      return v
    }
  } catch (e) {
    console.log(e);
  }
  return v
}

export function json_wrap_to_string(v) {
  try {
    if (is_json(v)) {
      return unicode_to_china(JSON.stringify(string_to_json(v)))

    } else {
      return v
    }

  } catch (e) {
    console.log(e);
  }
  return v
}


export function string_to_xml_wrap(v) {
  try {
    return vkbeautify.xml(v);
  } catch (e) {
    return v
  }
}

export function xml_wrap_to_string(v) {
  try {
    return vkbeautify.xmlmin(v);
  } catch (e) {
    return v
  }
}

export function is_json(str) {
  if (typeof str == 'string') {
    try {
      let obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }

    } catch (e) {
      return false;
    }
  }
}

export function check_string_type(v) {
  try {
    if (v.startsWith("<!DOCTYPE html")) {
      return 'HTML'
    } else if (v.startsWith("<")) {
      return 'XML'
    } else if (is_json(v)) {
      return 'JSON'
    } else {
      return 'TEXT'
    }
  } catch (e) {
    return 'TEXT'
  }
}

export function wrap_to_string(v, t) {
  let type = t || check_string_type(v)
  switch (type) {
    case 'JSON': {
      return json_wrap_to_string(v)
    }
    case 'XML': {
      return xml_wrap_to_string(v)
    }
    case 'HTML': {
      return xml_wrap_to_string(v)
    }
  }
  return v
}

export function string_to_wrap(v, t) {
  let type = t || check_string_type(v)
  switch (type) {
    case 'JSON': {
      return string_to_json_wrap(v)
    }
    case 'XML': {
      return string_to_xml_wrap(v)
    }
    case 'HTML': {
      return string_to_xml_wrap(v)
    }
  }
  return v
}

export function string_to_json(v) {
  try {
    if (is_json(v)) {
      return v
    } else {
      return v
    }
  } catch (e) {
    return v
  }
}

export function unicode_to_china(input) {
  try {
    return input.replace(/\\\\u([0-9a-fA-F]{2,4})/g, function (string, matched) {
      return String.fromCharCode(parseInt(matched, 16))
    })
  } catch (e) {
    console.log(e);
  }
  return input
}

然后在 editor目录下创建一个组件 我这里叫 index.vue

参考代码如下

<template>
  <div>
    <el-card class="box-card">
      <!-- 操作栏 -->
      <el-row slot="header" class="clearfix" v-if="toolbar == true">
        <el-col :span="5">
          <el-button type="primary" @click="toolsBarLeft">格式化</el-button>
          <el-button type="primary" @click="toolsBarRight">恢复</el-button>
        </el-col>
        <el-col :span="6">
          <el-select v-model="value_type">
            <el-option label="JSON" value="JSON"></el-option>
            <el-option label="TEXT" value="TEXT"></el-option>
            <el-option label="XML" value="XML"></el-option>
            <el-option label="HTML" value="HTML"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2" style="float:right">
          <el-button type="primary" v-clipboard:copy="contentBackup" @click="copy_value">复制</el-button>
        </el-col>
      </el-row>
      <!-- 编辑器 -->
      <div ref="vue_editor" style="height: 50vh;width: 100%"></div>
    </el-card>
  </div>
</template>
<style>
.box-card {
  margin: 20px;
}
.btn-hover {
  padding-left: 6px;
  padding-right: 6px;
}
.btn-hover:hover {
  background: #e0e0e0 !important;
}
.ace-xcode .ace_gutter {
  border-right: none !important;
  background: #fafafa !important;
}
.ace_content_disable {
  background: #fafafa !important;
}
</style>
<script>
// 引入ace代码编辑器
import ace from "brace/index";
import "brace/ext/emmet";
import "brace/ext/language_tools";
import "brace/mode/html";
import "brace/mode/json";
import "brace/mode/text";
import "brace/mode/xml";
import "brace/mode/javascript";
import "brace/theme/xcode";
import "brace/theme/terminal";
import "brace/snippets/javascript";
// 代码格式化方法
import {
  string_to_json_wrap,
  json_wrap_to_string,
  string_to_xml_wrap,
  check_string_type,
  wrap_to_string,
  string_to_wrap
} from "./data_format_utils";
// 主要代码
export default {
  name: "vue_editor",
  /**
   * 参数介绍:
   * value:(必填)双向绑定的数据;
   * theme:(非必填)ace编辑器主题默认xcode,可根据官网自行更换;
   * height:(必填)高度;
   * width:(必填)宽度;
   * options:(非必填)ace编辑器的设置
   * toolbar: (非必填)操作栏;
   * disable:(必填)是否启用编辑功能;
   * type:(非必填)json/xml/html/text,也支持更多,自行引用
   *
   */
  props: {
    value: {
      required: true
    },
    theme: {
      type: String,
      default: "xcode",
      required: false
    },
    options: Object,
    toolbar: {
      required: false,
      default: true,
      type: Boolean
    },
    disable: {
      required: false,
      type: Boolean,
      default: false
    },
    type: {
      required: false,
      type: String
    }
  },
  data() {
    return {
      editor: null,
      contentBackup: "",
      value_type: null,
      internalChange: false
    };
  },
  watch: {
    theme(v) {
      this.editor.setTheme("ace/theme/" + v);
    },
    options(v) {
      this.editor.setOptions(v);
    },
    height() {
      this.$nextTick(function() {
        this.editor.resize();
      });
    },
    width() {
      this.$nextTick(function() {
        this.editor.resize();
      });
    },
    value(v) {
      if (this.editor && !this.internalChange) {
        v = v && v !== null ? v : "";
        typeof v === "object" && (v = JSON.stringify(v));
        this.contentBackup = string_to_wrap(v);
        this.value_type = this.type || check_string_type(this.contentBackup);
        this.editor.session.setValue(this.contentBackup);
      }
    },
    value_type(nv) {
      switch (nv) {
        case "JSON": {
          this.contentBackup = string_to_json_wrap(this.contentBackup);
          this.editor.getSession().setMode("ace/mode/" + nv.toLowerCase());
          this.editor.session.setValue(this.contentBackup);
          break;
        }
        case "TEXT": {
          this.contentBackup = json_wrap_to_string(this.contentBackup);
          this.editor.getSession().setMode("ace/mode/" + nv.toLowerCase());
          this.editor.session.setValue(this.contentBackup);
          break;
        }
        case "XML": {
          this.contentBackup = string_to_xml_wrap(this.contentBackup);
          this.editor.getSession().setMode("ace/mode/" + nv.toLowerCase());
          this.editor.session.setValue(this.contentBackup);
          break;
        }
        case "HTML": {
          this.contentBackup = string_to_xml_wrap(this.contentBackup);
          this.editor.getSession().setMode("ace/mode/" + nv.toLowerCase());
          this.editor.session.setValue(this.contentBackup);
          break;
        }
        // 新增类别
        case "javascript": {
          this.editor.getSession().setMode("ace/mode/" + nv.toLowerCase());
          this.editor.session.setValue(this.contentBackup);
          break;
        }
      }
    },
    disable(v) {
      if (this.editor) {
        this.editor.setReadOnly(v);
        v
          ? this.$refs.vue_editor.classList.add("ace_content_disable")
          : this.$refs.vue_editor.classList.remove("ace_content_disable");
      }
    }
  },
  methods: {
    // 单位校验
    px(n) {
      if (/^\d*$/.test(n)) {
        return n + "px";
      }
      return n;
    },
    // 格式化
    toolsBarLeft() {
      this.contentBackup = string_to_wrap(this.contentBackup, this.value_type);
      this.editor.session.setValue(this.contentBackup);
    },
    // 数据转字符串
    toolsBarRight() {
      this.contentBackup = wrap_to_string(this.contentBackup, this.value_type);
      this.editor.session.setValue(this.contentBackup);
    },
    copy_value() {
      this.$copyText(this.contentBackup).then(
        () => {
          this.$message.success("已经复制到粘贴板!");
        },
        () => {
          this.$message.error("复制失败!");
        }
      );
    },
    onChange() {
      let error = false;
      let v;
      try {
        v = this.editor.getValue();
        error = false;
      } catch (err) {
        error = true;
      }
      if (error) {
        this.$emit("error");
      } else {
        if (this.editor) {
          this.internalChange = true;
          this.contentBackup = v;
          this.$emit("input", v);
          this.$nextTick(() => {
            this.internalChange = false;
          });
        }
      }
    },
    // 编辑器
    initView() {
      this.contentBackup = this.value && this.value !== null ? this.value : "";
      this.value_type = check_string_type(this.value);
      let vm = this;
      let lang = this.lang || "text";
      let theme = this.theme && this.theme !== "xcode" ? this.theme : "xcode";
      let editor_div = this.$refs.vue_editor;
      let editor = (vm.editor = ace.edit(editor_div));
      this.$emit("init", editor);
      editor.$blockScrolling = Infinity;
      editor.setOption("enableEmmet", false);
      editor.getSession().setMode("ace/mode/" + lang);
      editor.setTheme("ace/theme/" + theme);
      editor.getSession().setUseWrapMode(true);
      editor.setShowPrintMargin(false);
      editor.setValue(this.contentBackup);
      editor.on("change", vm.onChange);
      if (vm.options) editor.setOptions(vm.options);
      if (vm.disable) {
        editor.setReadOnly(true);
      }
      // 启用提示
      editor.setOption({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true
      });
    }
  },
  beforeDestroy() {
    this.editor.destroy();
    this.editor.container.remove();
  },
  mounted() {
    this.initView();
  }
};
</script>

然后在main.js全局引入依赖 参考代码如下


import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false
Vue.use(ElementUI);

// 引入复制
import VueClipboard from 'vue-clipboard2'
VueClipboard.config.autoSetContainer = true

const app = createApp(App);
app.use(VueClipboard)


去使用

<el-dialog
      title="常模配置"
      v-model="onlineEditOpen"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
    >
      <VueDataEditor
        @input="codeChange"
        :value="code"
        :disable="false"
        ref="editor"
      ></VueDataEditor>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
          <el-button @click="onlineEditOpen = false">取 消</el-button>
        </div>
      </template>
 </el-dialog>

import VueDataEditor from "@/components/editor";

let editor = ref()
let code = ref('<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <build>        <plugins>            <plugin>                <groupId>org.mybatis.generator</groupId>                <artifactId>mybatis-generator-maven-plugin</artifactId>                <version>1.3.2</version>                <configuration>                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>                    <verbose>true</verbose>                    <overwrite>true</overwrite>                </configuration>            </plugin>        </plugins>    </build></project>')

/** 在线编辑提交 */
const submitEditForm = () => {
  console.log(editor.value.contentBackup)
  onlineEditOpen.value = false
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Argenta99

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值