淘先锋技术网

首页 1 2 3 4 5 6 7

vue+elementui实现转换小工具

在实际工作中,常会用到将一块文本转成另一个文本的情况,就像发起一个请求,收到一个响应一样。

有很多在线工具就是实现这个功能,这里用vue+elementui实现一个自己的,顺便也学习一下vue和elementui,如果还有兴趣,可以继续扩展,以便提高自己的效率。

效果图:
jsaddin

jsaddin-search

源码

可以在DaggerTale清刚神话项目中找到这个实现:
DaggerTale清刚神话

  • 引入的在线库部分
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>DaggerTale插件调试工具</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta http-equiv="X-UA-Compatible" content="IE=EDGE"/>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.1/index.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.1/theme-chalk/index.css" rel="stylesheet"/>
    <script src="0.json"></script>
    <script src="./TemplateGenerator.js"></script>
  

</head>
  • 排版部分
<div id="app">
    <el-container>
        <el-header>
            <el-dropdown>
                <el-button type="primary" size="mini">导航<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item type="primary" icon="el-icon-thumb" >
                        <el-link :underline="false" href="../">首页</el-link>
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>

        </el-header>



        <!-- 选择功能-->
        <el-dialog style="text-align: left;"
            title="选择功能"
                    :visible.sync="isSelectFuncShowed"
                    width="70%">
                    
          <el-input v-model="keyword"
            maxlength="20"
            clearable
            @keyup.enter.native="triggerSearch()"
            placeholder=""> 
            <el-button slot="append" icon="el-icon-search" @click="triggerSearch()"></el-button>
          </el-input>
        
          <div>
            <h4>共{{resSearchFuncList.length}}个结果</h4>
            <el-menu>
              <el-menu-item v-for="(item,i) in resSearchFuncList" 
                @click="selectFunc(item.name)"
                index="i">{{item.des}}<span style="color:#909399">({{item.name}})</span></el-menu-item>
            </el-menu>
          </div>
        </el-dialog>



        <el-main>
          <el-row><h3>{{current.des}}({{current.name}})</h3></el-row>
          <el-row :gutter="20">
            <el-col :span="12" :xs="24">
                <h3>输入
                    <el-button type="primary" @click="openSelectFunc()" size="mini">
                      <i class="el-icon-more el-icon--right"></i></el-button>
                    <el-button size="mini" @click="reloadFunc()"><i class="el-icon-refresh"></i></el-button>
                    <el-button icon="el-icon-error" size="mini" 
                      @click="inData=''"></el-button>
                    <el-button size="mini" @click="loadExample()">载入示例</el-button>

                    <el-button type="primary" icon="el-icon-notebook-2" size="mini" 
                      @click="sendCmd()">转换</el-button>
                </h3>
        
                <el-input
                    type="textarea"
                    :rows="20"
                    placeholder="请输入内容"
                    v-model="inData">
                </el-input>
            </el-col>
            <el-col :span="12" :xs="24">
                <h3>预览
                    <el-button icon="el-icon-error" size="mini" 
                      @click="outData=''"></el-button>
                    <el-button icon="el-icon-d-arrow-left" size="mini" 
                      @click="swap()">交换</el-button>
                    <el-button icon="" size="mini" 
                      @click="beautify()">美化</el-button>
                </h3>

                <el-input
                    type="textarea"
                    :rows="20"
                    placeholder=""
                    v-model="outData">
                </el-input>
        
        
            </el-col>
          </el-row>
        </el-main>
    </el-container>
</div>

  • 脚本部分

function clone(obj) {
  var o;
  if (typeof obj == "object") {
    if (obj === null) {
      o = null;
    } else {
      if (obj instanceof Array) {
        o = [];
        for (var i = 0, len = obj.length; i < len; i++) {
          o.push(clone(obj[i]));
        }
      } else {
        o = {};
        for (var j in obj) {
          o[j] = clone(obj[j]);
        }
      }
    }
  } else {
    o = obj;
  }
  return o;
}

function loadJS(url, callback) {
  var script = document.createElement('script'),
    fn = callback || function() {};
  script.type = 'text/javascript';
  //IE
  if (script.readyState) {
    script.onreadystatechange = function() {
      if (script.readyState == 'loaded' || script.readyState == 'complete') {
        script.onreadystatechange = null;
        fn();
      }
    };
  } else {
    //其他浏览器
    script.onload = function() {
      fn();
    };
  }
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}


var vm = new Vue({
  el: '#app',
  data: {
    inData: exampleIn,
    outData: "",
    current:{
    	"des": "模板生成器",
    	"name": "TemplateGenerator",
    }, 
    dataDict: {},
    resSearchFuncList: [],
    isSearchDialogShowed:false,
    keyword: "",
    funcList: jsaddinsList,
    isSelectFuncShowed: false,
  },

  methods: {
    openSelectFunc: function() {
      this.resSearchFuncList = clone(this.funcList);
      this.keyword = "";
      this.isSelectFuncShowed = true;
    },
    reloadFunc: function() {
      var item = this.current;
      var fname = "./"+item["name"]+".js";
      if (item) {
        loadJS(fname,function(){
          vm.$message.success("已重新载入功能")
        });
      } else {
        this.$message.error("没有这个功能")
      }
    },
    loadExample: function(key) {
        vm.inData = exampleIn;
    },
    selectFunc: function(key) {
      var item = this.dataDict[key];
      var fname = "./"+item["name"]+".js";
      if (item) {
        loadJS(fname,function(){
          vm.$message.success("已载入功能: " + key)
          vm.isSelectFuncShowed = false;
          vm.current = item;
        });
      } else {
        this.$message.error("没有这个功能: " + key)
      }
    },
    swap:function(){
      var tmp = this.outData;
      this.outData = this.inData;
      this.inData = tmp;
    },
    beautify:function(){
      var tmp = this.outData;
      tmp =  JSON.stringify(JSON.parse(tmp), null, 2);
      this.outData = tmp;
    },

    triggerSearch: function() {
      var kw = this.keyword;
      var res = [];

      var isMatch = function(pkw, pitem) {
        pkw = pkw.toLowerCase();
        var name = pitem.name ? pitem.name.toLowerCase(): '';
        var des = pitem.des ? pitem.des.toLowerCase(): '';
        
        if (name.indexOf(pkw) != -1) {
          return true;
        }
        if (des.indexOf(pkw) != -1) {
          return true;
        }
        return false;
      }

      for (var i in this.funcList) {
        var item = this.funcList[i];
        if (isMatch(kw, item)) {
          res.push(item);
        }
      }
      this.resSearchFuncList = res;
    },

    sendCmd: function() {
      try {
        var s = this.inData
        this.outData = '';

        var out = convert(s);
        this.outData = out;


      } catch (e) {
        this.outData = e;
        return;
      }

    },


    refreshData: function() {
      this.genData();
    },
    genData: function(d) {
      var tips = [];
      for (var i in this.funcList) {
        var item = this.funcList[i];
        var key = item.name;
        if (this.dataDict[key]) {
          tips.push("重复的功能: " + key);
        }
        this.dataDict[key] = item;
      }
      // 功能默认第一个
      this.current = this.funcList[0];

      if (tips.length < 1) {
        return;
      }

      const h = this.$createElement;
      var newDatas = [];
      for (var i in tips) {
        newDatas.push(h('p', null, tips[i]));
      }
      this.$notify({
        title: '提示',
        message: h('div', null, newDatas),
        type: 'error',
        position: 'top-left'
      });
    }


  },
  mounted: function() {
      this.refreshData();
    } // end of mounted
});

其他说明

本文来自开源项目DaggerTale-清刚神话

DaggerTale-清刚神话项目地址:
https://gitee.com/ticktips/DaggerTale

转换小工具文件在jsaddins/下,包括0.html和0.json:
https://gitee.com/ticktips/DaggerTale/blob/develop/release/DaggerTale-v1.0.0-win-x86.zip