vue实现路由切换操作


vue中实现在路由切换后阻止后续代码的执行

    data(){
      return {
        routerLeave: false
      };
    },
   beforeRouteLeave(to, from, next) {
      this.routerLeave = true;
      next();
   },
   methods:{
    load()
    {
         Promise.all([
            this.getQpsOverview(),
            this.getWasteTimeOverview(),
            this.getErrorOverview()
      ]).then(() => {console.log('finish loading echarts')})
    },
    getQpsOverview(){
           return this.$http.getQpsdata({
            "appname":this.appname,
            "startTime":this.startTtime,
            "endTime":this.endTime
           },{notify:true})
          .then((data) => {
            if (this.routerLeave) {
              return;
            }
         this.qpsChart = echarts.init(document.getElementById('chart_example'));
            this.qpsChart.setOption(utils.qpsChartOptions(x_data,y_data_qps,y_data_dayqps,y_data_weekqps));
          });
    }        
  }
View Code

 

ElementUI tooltip显示动态数据

  <template slot="operation" slot-scope="{scope}">
                <el-tooltip class="item" effect="dark" :content="scope.row.jylsh" placement="top-start">
                  <a @click="showDetail(scope.row.jylsh)">{{scope.row.jylsh}}</a>
                 </el-tooltip>
</template>
View Code

 

Vue实现数据的查询和保存

  getEsconfig:{
     url: '/sysconfig/es/show',
     method: 'GET',
     description: '获取Es的配置信息'
  },
  saveEsConfig:{
     url: '/sysconfig/es/show',
     method: 'POST',
     description: '保存Es的配置信息'
  }
vue路由配置
<template>
 <div class="otherConfigure">
    <el-form ref="form" label-width="180px" label-position="left" label-suffix=":">
      <el-form-item label="Elasticsearch API地址">
        <template>
          <el-input
            v-model="esurl"
            size="medium"
            placeholder="eg:http://192.168.1.1:9200"
            style="width:350px;margin-right:15px;margin-bottom:15px">
         </el-input>
         &nbsp;&nbsp;
         <el-button type="primary" @click="saveConfig">保存</el-button>
        </template>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>

  export default {
    components: {
    },
    data() {
      return {
        esurl:"",
        esid:""
      }
    },
    props: {},
    mounted() {
      //加载面包屑导航
      this.breadcrumbList = [
        {
          path: '',
          text: '系统配置'
        },
        {
          path: '/sysconfig/esconfig',
          text: 'es配置'
        }
        ];
        this.getEsConfig();
    },
    methods: {
      saveConfig()
      {
        if(this.esurl == "")
        {
          this.$message({
              showClose: true,
              message: 'Elasticsearch API地址不能为空!',
              type: 'warning'
           });
        }
        else
        {
          return this.$http.saveEsConfig({
           "esurl":this.esurl,"id":this.esid},{notify:true}).then((data) => {
              this.$message.success(data);
          });
        }
      },
      getEsConfig()
      {
        return this.$http.getEsconfig({
           },{notify:true}).then((data) => {
              this.esurl=data.esurl;
              this.esid=data.id;
          });
      }
  }
}
</script>
<style lang='scss' scoped>
 .otherConfigure {
    p {
      color: #666666;
      font-size: 14px;
    }
  }
</style>
vue前端代码
    @method_decorator(authDecorator)
    def get(self, request):
        es = models.EsConfig.objects.first()
        serializer = EsConfigSerializer(es)
        return JsonResponse(outMessage(data=serializer.data))

    @method_decorator(authDecorator)
    def post(self, request):
        ERROR_CODE = 'ESCONFIGADD_ERROR'
        body = str(request.body, encoding='utf-8')
        jsBody = json.loads(body)
        Id = jsBody.get('id', False)
        if not Id:
            return JsonResponse(outMessage(code=ERROR_CODE, message='ID不存在'))
        oldObj = models.EsConfig.objects.get(id=int(Id))
        serializer = EsConfigSerializer(data=jsBody,instance=oldObj)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    obj = serializer.save()
            except Exception as e:
                return JsonResponse(outMessage(code=ERROR_CODE, message=str(e)))
        else:
            return JsonResponse(outMessage(code=ERROR_CODE, message=serializer.errors))
        return JsonResponse(outMessage(data="Elasticsearch API地址保存成功!"))



########保存和修改实例####################
修改数据的时候需要在调用save函数的时候把instance参数传递过去
instance参数表示数据库中原来的数据对象 


新增数据
    @method_decorator(authDecorator)
    def post(self, request):
        ERROR_CODE = 'ESCONFIGADD_ERROR'
        body = str(request.body, encoding='utf-8')
        jsBody = json.loads(body)
        serializer = EsConfigSerializer(data=jsBody)
        print(serializer)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    obj = serializer.save()
            except Exception as e:
                return JsonResponse(outMessage(code=ERROR_CODE, message=str(e)))
        else:
            return JsonResponse(outMessage(code=ERROR_CODE, message=serializer.errors))
        return JsonResponse(outMessage())

更新数据
    @method_decorator(authDecorator)
    def post(self, request):
        ERROR_CODE = 'ESCONFIGADD_ERROR'
        body = str(request.body, encoding='utf-8')
        jsBody = json.loads(body)
        Id = jsBody.get('id', False)
        if not Id:
            return JsonResponse(outMessage(code=ERROR_CODE, message='ID不存在'))
        oldObj = models.EsConfig.objects.get(id=int(Id))
        serializer = EsConfigSerializer(data=jsBody,instance=oldObj)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    obj = serializer.save()
            except Exception as e:
                return JsonResponse(outMessage(code=ERROR_CODE, message=str(e)))
        else:
            return JsonResponse(outMessage(code=ERROR_CODE, message=serializer.errors))
        return JsonResponse(outMessage(data="sucess"))
后端API

 

前端把后端字符串转成JSON对象

saveConfig()
      {
          return this.$http.savefazhiConfig({
           "esurl":'{"wasteTime":'+this.wasteTime+',"errCount":'+this.errCount+'}',"id":this.esid,"type":1},{notify:true}).then((data) => {
              this.$message.success(data);
          });
      }
前端保存到后端
getfazhiConfig()
      {
        return this.$http.getfazhiConfig({
           },{notify:true}).then((data) => {
            console.log(data.esurl);
            console.log(data.esurl.replace(/'/g,'"'));
            const obj=JSON.parse(data.esurl.replace(/'/g,'"'));
            this.wasteTime=obj.wasteTime;
            this.errCount=obj.errCount;
            this.esid=data.id;
        });
      }
#js在把json字符串转成对象的时候需要单引号变成双引号
#否则会转换异常
View Code

 

Vue实现给table的行动态设置背景色

#table的html
           <!-- 主机列表 -->
        <el-table
        :data="mergeData"
        @row-click="openDetails"
        highlight-current-row
        style="width: 100%"
        :row-class-name="tableRowClassName"
        :default-sort = "{prop: 'hostname', order: 'descending'}"
        >
        <el-table-column
          prop="hostname"
          label="实例列表"
          sortable
          width="130"
          >
        </el-table-column>
        <el-table-column
         prop="responseTime"
         label="响应时间"
         sortable
         width="80">
        </el-table-column>
       <el-table-column
         prop="requestCount"
         label="请求数"
         sortable
         width="72">
       </el-table-column>
       <el-table-column
         prop="errRequest"
         label="错误数"
         sortable
         width="72">
       </el-table-column>
        </el-table>




#js
getHostsBydb()
      {
         this.mergeData=[];
         Promise.all([
          this.$http.getHostList({},{notify:true}).then((data) => {
               this.tableData=data.list;
           }),
           this.getHosts(),
           this.getfazhiConfig()
         ]).then(() => {
           for(let t=0;t<this.tableData.length;t++)
             {   
                 let flag=true;
                 for(let j=0;j<this.estableData.length;j++)
                 {   
                     if(this.tableData[t].hostname == this.estableData[j].hostname)
                     {
                       flag=false;
                       let passfazhi=false;
                       if(this.estableData[j].responseTime>=this.wasteTime || this.estableData[j].errRequest >= this.errCount)
                       {
                            passfazhi=true;
                       }
                       this.mergeData.push({"hostname":this.tableData[t].hostname,"responseTime":this.estableData[j].responseTime+"ms","requestCount":this.estableData[j].requestCount,"errRequest":this.estableData[j].errRequest,"IsConnect":true,"passfazhi":passfazhi});
                       break;
                     }
                 }
                 if(flag==true)
                 {
                  this.mergeData.push({"hostname":this.tableData[t].hostname,"responseTime":"0ms","requestCount":0,"errRequest":0,"IsConnect":false,"passfazhi":true});
                }
              }
          });
      }

tableRowClassName({row, rowIndex}) 
     {
        if (row.IsConnect == false) {
          return 'error-row';
        } 
        else if(row.passfazhi == true) {
          return 'warning-row';
        }
        return '';
      }
html和js
.el-table {
  tr.current-row{
    background-color: #f19944;
    &.error-row,&.warning-row, &.success-row {
      td {
        .cell {
          color: #333333;
        }
      }
    }
  }
  tr.error-row,tr.warning-row, tr.success-row{
    td {
      .cell {
        color: #ffffff;
      }
    }
    &:hover {
      td {
        .cell {
          color: #333333;
        }
      }
    }
  }
  tr.error-row {
    background-color: #F56C6C;
  }
  tr.warning-row {
    background-color: #E6A23C;
  }
  tr.success-row{
    background-color: green;
  }
scss
        res = self.es.search(body=body)
        hlist=[]
        for host in res["aggregations"]["res"]["buckets"]:
            wastetime = str(host["waste_time"]["value"])
            requests = host["doc_count"]
            err_express = [i["doc_count"] for i in host["visit"]["buckets"] if i["key"] == "false"]
            errcount = err_express[0] if len(err_express) > 0 else 0
            hlist.append({"hostname":host["key"],"responseTime":wastetime,"requestCount":requests,"errRequest":errcount})

        hlist.append({"hostname":"111","responseTime":1000,"requestCount":3333,"errRequest":2000})
        hlist.append({"hostname": "222", "responseTime": 900, "requestCount": 55555, "errRequest": 5000})
        hlist.append({"hostname": "333", "responseTime": 500, "requestCount": 5665, "errRequest": 20})
        data = {'code': 'SUCCESS', 'message': '', 'data': {"list":hlist}}
        return data
python

.el-table {
  tr.current-row{
    background-color: #f19944;
    &.error-row,&.warning-row, &.success-row {
      td {
        .cell {
          color: #333333;
        }
      }
    }
  }
  tr.error-row, tr.success-row{
    td {
      .cell {
        color: red;
      }
    }
    &:hover {
      td {
        .cell {
          color: #333333;
        }
      }
    }
  }
  tr.warning-row, tr.success-row{
    td {
      .cell {
        color: #E6A23C;
      }
    }
    &:hover {
      td {
        .cell {
          color: #333333;
        }
      }
    }
  }
}
样式2

 

vue实现密码加密保存

 savezbxConfig()
      {
        this.$refs.form.validate()
          .then(() => {
           const {zabbixurl,zabbixuser,zabbixpasswd} = this.form;
           return this.$http.saveZabbixConfig({
           "esurl":'{"zabbixurl":"'+zabbixurl+'","username":"'+zabbixuser+'","passwd":"'+zabbixpasswd+'"}',"id":this.zbxid,"type":3},{notify:true}).then((data) => {
              this.$message.success(data);
          });
        });
      }


 getzbxconfig()
      {
        return this.$http.getZabbixConfig({
           },{notify:true}).then((data) => {
              const obj=JSON.parse(data.esurl.replace(/'/g,'"'));
            this.form.zabbixurl=obj.zabbixurl;
            this.form.zabbixuser=obj.username;
            this.form.zabbixpasswd=obj.passwd;
            this.zbxid=data.id;
          });
      }
vue
    @method_decorator(authDecorator)
    def get(self, request):
        zbx= models.EsConfig.objects.filter(type=3).first()
        zbx_config=json.loads(zbx.esurl)
        zbx_config["passwd"]=AesAuth.decrypt(zbx_config["passwd"])
        zbx.esurl=json.dumps(zbx_config)
        serializer = EsConfigSerializer(zbx)
        return JsonResponse(outMessage(data=serializer.data))

    @method_decorator(authDecorator)
    def post(self, request):
        ERROR_CODE = 'ZBXCONFIGADD_ERROR'
        body = str(request.body, encoding='utf-8')
        jsBody = json.loads(body)
        Id = jsBody.get('id', False)
        configstr=jsBody.get("esurl",{})
        configbody=json.loads(configstr)
        configbody["passwd"]=AesAuth.encrypt(configbody["passwd"].encode("utf-8")).decode()
        jsBody["esurl"]=json.dumps(configbody)
        if Id:
            oldObj = models.EsConfig.objects.get(id=int(Id))
            serializer = EsConfigSerializer(data=jsBody,instance=oldObj)
        else:
            serializer = EsConfigSerializer(data=jsBody)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    obj = serializer.save()
            except Exception as e:
                return JsonResponse(outMessage(code=ERROR_CODE, message=str(e)))
        else:
            return JsonResponse(outMessage(code=ERROR_CODE, message=serializer.errors))
        return JsonResponse(outMessage(data="ZABBIX配置保存成功!"))
python
import datetime, requests, json, re,time

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from Crypto import Random


class AesAuth (object):
    KEY = "aaaa"
    MODE = AES.MODE_CFB
    
    @staticmethod
    def genkey():
        value = AesAuth.KEY
        while len (value) % 16 != 0:
            value += '\0'
        return str.encode (value)
    
    @classmethod
    def encrypt(cls, strs):
        # 生成随机初始向量IV
        iv = Random.new ().read (AES.block_size)
        cryptor = AES.new (cls.genkey (), cls.MODE, iv)
        ciphertext = cryptor.encrypt (strs)
        return b2a_hex (iv + ciphertext)
    
    @classmethod
    def decrypt(cls, ciphertext):
        ciphertext = a2b_hex (ciphertext)
        iv = ciphertext[0:AES.block_size]
        ciphertext = ciphertext[AES.block_size:len (ciphertext)]
        cryptor = AES.new (cls.genkey (), cls.MODE, iv)
        plaintext = cryptor.decrypt (ciphertext).decode ("utf-8")
        return plaintext
加密算法

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM