项目开发的各种技能使用

417 阅读3分钟

js获取浏览器内核信息和IP地址

获取IP地址

  • 1 在html引入
 <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
  • 2在项目中直接使用
returnCitySN.cip

获取浏览器内核信息

const getBrowInfo = () => {
  var agent = navigator.userAgent.toLowerCase();
  var arr = '';
  var regStr_edge = /edg\/[\d.]+/gi;
  var regStr_ie = /trident\/[\d.]+/gi;
  var regStr_ff = /firefox\/[\d.]+/gi;
  var regStr_chrome = /chrome\/[\d.]+/gi;
  var regStr_saf = /safari\/[\d.]+/gi;
  var regStr_opera = /opr\/[\d.]+/gi;
  //IE
  if (agent.indexOf("trident") > 0) {
    arr = agent.match(regStr_ie)[0].split('/')[0]
    return arr;
  }
  //Edge
  if (agent.indexOf('edg') > 0) {
    // arr = agent.match(regStr_edge)[0].split('/')[0]
    arr = 'edge'
    return arr;
  }
  //firefox
  if (agent.indexOf("firefox") > 0) {
    arr = agent.match(regStr_ff)[0].split('/')[0]
    return arr;
  }
  //Opera
  if (agent.indexOf("opr") > 0) {
    arr = agent.match(regStr_opera)[0].split('/')[0]
    return arr;
  }
  //Safari
  if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
    arr = agent.match(regStr_saf)[0].split('/')[0]
    return arr;
  }
  //Chrome
  if (agent.indexOf("chrome") > 0) {
    arr = agent.match(regStr_chrome)[0].split('/')[0]
    return arr;
  } else {
    arr = '其他'
    return arr;
  }
}

vue+element的用法

1:列表的展示与选择

    html部分:
    <el-row class="userBoxHead">
          <el-col :span="1">
            <div class="grid-content ">
            <el-checkbox v-model="allProduct" title="全选" @change="getAllProductInfo">&nbsp;</el-checkbox>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="grid-content ">
              <span>产品图</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content ">
              <span>名称</span>
            </div>
          </el-col>
        </el-row>
        <el-checkbox-group v-model="choiceProductList" @change="changeProductList">
             <el-row
                class="userBoxList"
                v-for="(elem,index) in proInfoList"
                :key="'product'+index"
                v-show="proInfoList.length>0"
              >
                <el-col :span="1">
                  <div class="grid-content bg-purple">
                    <el-checkbox :label="elem.id" :disabled="elem.noChecked">&nbsp;</el-checkbox>
                  </div>
                </el-col>
                 <el-col :span="11">
            <div class="grid-content ">
              <span>{{elem.img}}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content ">
              <span>{{elem.name}}</span>
            </div>
          </el-col>
        </el-row>
    </el-checkbox-group>
    //1:使用element的Layout布局 在表头设置名称和全选功能
    //2:在数据展示页用element的el-checkbox-group 来实现全选
    
    js 部分
     //点击全选,获取当前展示的产品信息
        getAllProductInfo() {
            this.choiceProductList = []
            if (this.allProduct) {
                let self = this
                $.each(this.proInfoList, function (i, row) {
                    self.choiceProductList.push(row.id)
                   self.getSpaceBoxInfo(row,i)
                })
            }
        },
      //判断当前选中列表的数是否全部选择
      changeProductList(val){
      //全选情况下 全选框显示为true
          if(val.length==this.proInfoList.length){
              this.allProduct=true
          }else{
              this.allProduct=false
          }
      }
    

2:Dialog 对话框(可移动弹窗)


html部分
<el-dialog
        title="云盘附件"
        :close-on-click-modal="false"
        :visible.sync="popup7"
        size="tiny"
        :modal="false"
        class="wl-popup7 dialogOne myOrderIcon"
        :before-close="popup7Cance"
      >
      <div>
      内容区域
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="popup7Config">确认</el-button>
          <el-button @click="popup7Cance">取 消</el-button>
        </span>
      </el-dialog>
    js部分
      //  弹框居中设置及弹框拖拽
		/******************************/
		var windowW = $(window).width();
		//弹框拖拽设置
		var dialogDrag = function() {
			//				第一层的弹框
			$(".dialogOne").find('.el-dialog__header').addClass('handle1')
			//				第二层的弹框
			$(".dialogTwo").find('.el-dialog__header').addClass('handle2').removeClass('handle1')
			//				第三层的弹框
			$(".dialogThree").find('.el-dialog__header').addClass('handle3').removeClass('handle1').removeClass('handle2')
			$(function() {
				$(".dialogOne .el-dialog--tiny").Tdrag({
					scope: "body",
					handle: " .handle1"
				});
				$(".dialogTwo .el-dialog--tiny").Tdrag({
					scope: "body",
					handle: ".handle2"
				});
				$(".dialogThree .el-dialog--tiny").Tdrag({
					scope: "body",
					handle: ".handle3"
				});
			})
		}

			//调整窗口大小时,设置弹框居中
			var windowDialogCenter = function() {
				//此页弹框数
				$(window).resize(function() {
					var dialogLength = $('.el-dialog').length;
					windowW = $(window).width();
					for(var a = 0; a < dialogLength; a++) {
						var left = (windowW - $('.el-dialog').eq(a).outerWidth()) / 2;
						$('.el-dialog').eq(a).css({
							'top': '15%',
							'left': left
						});
					}
				});
				$(window).resize();
			}
			var dialog = '',
				dialogLength = 0;
			//点击关闭弹出框时,设置弹框居中
			var dialogCenter = function() {
				//清除弹框的居中样式
				$('.el-dialog').css({
					'transform': 'translateX(0)',
					'left': ''
				})
				//调整窗口大小时,设置弹框居中
				windowDialogCenter();
				//点击关闭,取消按钮时,设置父元素弹框居中;点击确认按钮,因为确认会触发许多事件,去具体页面添加,
				$('.el-dialog__headerbtn,.el-button--default').on('click', function() {
					var checkbox = $(this).parents('.el-dialog').find("input[type=checkbox]");
					checkbox.prop("checked", false);
					checkbox.parent(".checkboxStyle").removeClass('onCheckbox');
					var one = $(this).parents('.el-dialog__wrapper').hasClass('dialogOne'),
						two = $(this).parents('.el-dialog__wrapper').hasClass('dialogTwo'),
						three = $(this).parents('.el-dialog__wrapper').hasClass('dialogThree');
					if(one) {
						dialog = $('.dialogOne');
						dialogLength = $('.dialogOne').length;
					} else
					if(two) {
						dialog = $('.dialogTwo');
						dialogLength = $('.dialogTwo').length;
					} else if(three) {
						dialog = $('.dialogThree');
						dialogLength = $('.dialogThree').length;
					}
					dialogCenterDelay();
				})
			}

			//点击确认取消关闭时,设置弹框居中
			var dialogCenterDelay = function(parents) {
				setTimeout(function() {
					$(window).resize(function() {
						windowW = $(window).width();
						for(var a = 0; a < dialogLength; a++) {
							var left = (windowW - dialog.eq(a).children('.el-dialog').outerWidth()) / 2;
							dialog.eq(a).children('.el-dialog').css({
								'top': '15%',
								'left': left
							});
						}
						dialog = '', dialogLength = 0
					});
					$(window).resize();
				}, 300)
			}

3:element 的Tooltip 文字提示

html
   <el-tooltip placement="left-end" v-if="showChoiceProduct.length>1 ">
        <div slot="content" class="productTool">
            <ul>
              <li>
                <span>已选产品:</span>
              </li>
              <li v-for="(row,dex) in showChoiceProduct" :key="'hover'+dex">
                <span :title="row.name">{{row.name}}</span>
              </li>
            </ul>
          </div>
          <div v-show="showChoiceProduct.length>0">
            <span
              v-if="showChoiceProduct.length>1"
              class="blureText"
              @click="showProduct"
            >{{showChoiceProduct.length}}个产品</span>
        </div>
        
    </el-tooltip>

iview的使用

使用form表单

使用格式

     <Form :model="equipmentInfo"
            :rules="accessEquipmentValidate"
            :label-width="130"
            ref="accessEquipmentForm">
        <FormItem label="设备类型"
                  prop="equipmentType">
          <Select @on-change="changeEquipType"
                  v-model="equipmentInfo.equipmentType"
                  style="width:250px;">
            <Option :value="elem.type"
                    v-for="(elem,index) in equipmentTypeListInfo"
                    :key="'equModal'+index">{{elem.name}}</Option>
          </Select>
        </FormItem>
        <!-- 根据设备类型获取型号 -->
        <FormItem label="设备型号"
                  prop="equipmentModal">
          <Select @on-change="changeEquipType"
                  v-model="equipmentInfo.equipmentModal"
                  style="width:250px;">
            <Option :value="elem.id"
                    v-for="(elem,index) in equipmentModalList"
                    :key="'equModal'+index">{{elem.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称"
                  prop="equipmentName">
          <Input v-model="equipmentInfo.equipmentName"
                 placeholder="请输入设备名称"
                 style="width: 250px;"
                 :maxlength="20"></Input>
        </FormItem>
      </Form>
    
    data () {
    const validatePassType = (rule, value, callback) => {
      if (value == '-1') {
        callback(rule.message)
      } else {
        callback();
      }
    };
    return {
      equipmentInfo: {
        equipmentType: '',//设备类型
        equipmentModal: '',//设备型号
      },//表格的信息
      accessEquipmentValidate: {
        equipmentType: [{
          required: true, validator: validatePassType, message: "请选择", trigger: "change"
        }],//选择器验证
        equipmentName: [
          {
            required: true, transform: value => value ? value.trim() : '', message: "输入不能为空", trigger: "blur"
          }
        ]
      },//验证表单信息
      equipmentTypeListInfo: [],//设备类型列表
      equipmentModalList: [],//设备型号
    }
  },
  
  //验证
  methods:{
       let refsValid = false;
      //对门禁设备进行验证
      this.$refs['accessEquipmentForm'].validate(val => {
        if (val) {
        } else {
          this.$Message.warning({
            background: true,
            content: "请填写相关信息!"
          });
          refsValid = true;
          return false;
        }
      })
      if (refsValid) {
        return false;
      } 
  } 
  

vue使用过程的报错

1 安装全局vue_cli 3.0 的报错

报错代码:

! errno -4048
npm ERR! syscall mkdir
npm ERR! Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'
//报错重要信息:
//operation not permitted,:不允许操作,
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended)

报错信息与解决方案:

当前不允许操作,这时候应该用管理员身份进入CMD,便可解决 window10下,通过搜索框搜索cmd,显示后右击从管理员身份运行即可

vant的使用

设置省市区

运用:业务组件中的Area

  <van-area :area-list="areaList"
        @confirm="confirmArea"
        @cancel="cancelArea"
        :columns-placeholder="['请选择', '请选择', '请选择']"
        ref="area"
        :value="valueArea"
    />
    
js:
 data () {
    return {
      areaList: areaList,
      valueArea:'110100',//默认值指向北京
}
 methods:{
    //确认省市区的选择
    confirmArea(e){
      //判断当前用户有无选择完整的省市区,否则重置
      if(e[0] && e[1] && e[2] && e[2].code!=='' ){
        this.valueArea=e[2].code
      }else{
        this.$refs.area.reset()
      }
    },
  }

json的数据存在码云: gitee.com/wyrweb/code…

样式如下:

canvas的使用

1:使用canvas转换在线图片为base64

 //将在线图片转化为base64的图片
    getBase64Image (img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d"); //获取绘图上下文环境
      ctx.drawImage(img, 0, 0, img.width, img.height); //在canvas中画图
      var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(); // 获取到图片的格式
      var dataURL = canvas.toDataURL("image/" + ext); //可选其他值 image/jpeg
      return dataURL;
    },
    main (src, cb) {
      let _this = this
      var image = new Image();
      image.src = src; // 处理缓存
      image.setAttribute('crossOrigin', 'anonymous');
      // image.crossOrigin = "*";                 // 支持跨域图片
      image.onload = function () {
        var base64 = _this.getBase64Image(image);
      }
    },

2、使用canvas让当前页成为一张图片

  • 1:安装html2canvas
  • 2:在当前使用的页面中引入
  • 3: 在当前页获取所有所需信息后进行图片的绘制
<div  id="personal">
<div id="perBox"></div>
</div>



import html2canvas from 'html2canvas'
   //htmlTocanvas
    createImage () {
      const dom = document.getElementById('perBox')
      const Canvas = document.createElement('canvas')
      const width = document.body.offsetWidth // 可见屏幕的宽
      const height = document.body.offsetHeight // 可见屏幕的高
      const scale = 1 // 设备的devicePixelRatio
      // 将Canvas画布放大scale倍,然后放在小的屏幕里,解决模糊问题
      Canvas.width = width * scale
      Canvas.height = height * scale
      Canvas.getContext('2d').scale(scale, scale)
      html2canvas(dom, {
        canvas: Canvas,
        scale,
        useCORS: true,
        logging: true,
        width: width + 'px',
        hegiht: height + 'px'
      }).then(canvas => {
        const context = canvas.getContext('2d')
        // 关闭抗锯齿形
        context.mozImageSmoothingEnabled = false
        context.webkitImageSmoothingEnabled = false
        context.msImageSmoothingEnabled = false
        context.imageSmoothingEnabled = false
        // canvas转化为图片
        const img = this.canvas2Image(canvas, canvas.width, canvas.height)
        let personalDom = document.getElementById('personal')
        personalDom.appendChild(img)
        img.style.cssText =
          'width:100%;height:100%;position:absolute;top:0;left:0;right:0;bottom:0;opacity:0;'
      })
    },
    //canvasToimage
    canvas2Image (canvas, width, height) {
      const retCanvas = document.createElement('canvas')
      const retCtx = retCanvas.getContext('2d')
      retCanvas.width = width
      retCanvas.height = height
      retCtx.drawImage(canvas, 0, 0, width, height, 0, 0, width, height)
      const img = document.createElement('img')
      img.src = retCanvas.toDataURL('image/jpeg') // 可以根据需要更改格式
      return img
    },