work遇到的问题

        写给自己的话,工作肯定会遇到困难,希望你可以平静而细心的去解决问题,而不是浮躁的抓耳挠腮,事情总有解决的办法,我们努力是为了追上那个更好的我,所以加油吧,追求源于热爱~

Vue2

1.安装依赖启动项目报错

解决 less-loader You may need to install it
解决 Node Sass version 6.0.1 is incompatible with ^4.0.0.

npm install less less-loader --save-dev

npm install less-loader
原因: less-loader安装的版本过高
解决方案:   1.npm uninstall less-loader
            2.npm install less-loader@6.0.0
解决:Node Sass版本过高
            1.npm uninstall less-loader
            2.npm install node-sass@4.14.1

Failed to resolve loader: less-loader You may need to install it 的解决方法,四种,可以都试试!_浮岫的博客-CSDN博客

2. Cascader 城市级联选择器

直接npm element给的数据实现城市选择器,下面是结合了选择选择城市后给到的value处理中城市

<template>
  <div id="app">
    <el-cascader
      size="large"
      :options="options"
      v-model="selectedOptions"
      @change="handleChange">
    </el-cascader>
  </div>
</template>
 
<script>
  //npm install element-china-area-data -S
  import { regionData } from 'element-china-area-data'
  import provinceAndCity from '../utils/province.json'//阿里云盘里面
  export default {
    data () {
      return {
        search:{current:1,size:6},
        options: regionData,
        selectedOptions: [],
        provinceAndCity
      }
    },
 
    methods: {
      handleChange (value) {
        this.search.province = ""
        this.search.city = ""
        this.search.district = ""  
        for (var k = 0, lengthk = provinceAndCity.length; k < lengthk; k++) { 
          //确定省
          if(provinceAndCity[k].code == value[0]){  
            this.search.province = provinceAndCity[k].name; 
            if(provinceAndCity[k].cityList && value.length>=2 && value[1]!=""){ 
              for (var i = 0, lengthi = provinceAndCity[k].cityList.length; i < lengthi; i++){
                //确定市
                if(provinceAndCity[k].cityList[i].code == value[1] || provinceAndCity[k].cityList.length == 1 ){
                  this.search.city = provinceAndCity[k].cityList[i].name; 
                  //确定区
                  if(provinceAndCity[k].cityList[i].areaList && value.length==3 && value[2]!=""){
                    for(var j = 0,lengthj = provinceAndCity[k].cityList[i].areaList.length ; j<lengthj;j++){
                      if(provinceAndCity[k].cityList[i].areaList[j].code == value[2]){
                        this.search.district = provinceAndCity[k].cityList[i].areaList[j].name; 
                        break;
                      }
                    }
                  }
                  break;
                }
              }
            }
            break;
          }
        } 
        console.log(value)
        console.log(this.search.province+ this.search.city+this.search.district)
      },
    }
  }
</script>

 直接文件形式导入使用 import regionData from '@/utils
文件在阿里云盘

Vue+ElemetUI的省市区三级联动的方法(区域码最终转为中文地址)_vue pcaa地区编码转文字_洛阳八中我最棒的博客-CSDN博客

级联选择器(el-cascader)动态加载(lazyLoad)实现省市区三级选择_el-cascader lazyload_后海 0_o的博客-CSDN博客

3. el-tooltip不显示

因为el-tooltip层级问题导致不显示,直接设置css属性z-index,并且开启position: relative;定位配合使用z-index才能生效

<template slot="label">
     <span>{{ $t("message")["上传文件"] }}</span>
        <el-tooltip class="tip-text" effect="dark" placement="right" >
           <div slot="content">上传图片大小不要超过200k,否则可能导致上传失败</div>
         <i class="el-icon-question" style="font-size: 16px; vertical-align: middle"></i>
        </el-tooltip>
</template>

4.百度地图定位选点弹出经纬度

//view页面  npm install vue-baidu-map --save 
<template>
  <div>
    <baidu-map
      style="display: flex; flex-direction: column-reverse"
      id="allmap"
      @ready="mapReady"
      @click="getLocation"
      :scroll-wheel-zoom="true"
    >
      <div style="display: flex; justify-content: center; margin: 15px">
        <bm-auto-complete
          v-model="searchJingwei"
          :sugStyle="{ zIndex: 999999 }"
        >
          <el-input
            v-model="searchJingwei"
            style="width: 300px; margin-right: 15px"
            placeholder="输入地址"
          ></el-input>
        </bm-auto-complete>
        <el-button type="primary" @click="getBaiduMapPoint">搜索</el-button>
      </div>
      <bm-map-type
        :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
        anchor="BMAP_ANCHOR_TOP_LEFT"
      >
      </bm-map-type>
      <bm-marker
        v-if="infoWindowShow"
        :position="{ lng: longitude, lat: latitude }"
      >
        <bm-label
          content=""
          :labelStyle="{ color: 'red', fontSize: '24px' }"
          :offset="{ width: -35, height: 30 }"
      /></bm-marker>
      <bm-info-window
        :position="{ lng: longitude, lat: latitude }"
        :show="infoWindowShow"
        @clickclose="infoWindowClose"
      >
        <p>纬度:{{ this.latitude }}</p>
        <p>经度:{{ this.longitude }}</p>
      </bm-info-window>
    </baidu-map>
  </div>
</template>

<script>
export default {
  data () {
    return {
      searchJingwei:'',
      infoWindowShow:false,
      longitude:'',
      latitude:'',
      point:''
    }
  },
  methods: {
    //地图初始化
    mapReady({ BMap,map}) {
      let geolocation=new BMap.Geolocation()
      geolocation.getCurrentPosition((res)=>{
        console.log(res,1111);
      })
      // 选择一个经纬度作为中心点
      this.point = new BMap.Point(113.27, 23.13);
      map.centerAndZoom(this.point, 12);
      this.BMap=BMap
      this.map=map
    },
    //点击获取经纬度
    getLocation(e){
      this.longitude=e.point.lng
      this.latitude=e.point.lat
      this.infoWindowShow=true
    },
    getBaiduMapPoint(){
      let that=this
      let myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(this.searchJingwei,function(point){
        console.log(point);
        if(point){
          that.map.centerAndZoom(point,15)
          that.latitude=point.lat
          that.longitude=point.lng
          that.infoWindowShow=true
        }
 
      })
    },
    //信息窗口关闭
    infoWindowClose(){
      this.latitude=''
      this.longitude=''
      this.infoWindowShow=false
    },
  },
}
</script>
<style  scoped>
#allmap {
  height: 450px;
  width: 100%;
  margin: 10px 0;
}
</style> 
//main

import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {ak:"4bmVWiLUUDtGDshxmzPIFbhqUa1NC9Dt&callback="}) //填写百度地图注册获取的ak

5.用心思考

6.刷新当前页面最佳解决方案

利用v-if的删除DOM走生命周期的特性,完成刷新当前页面

<template>
  <div id="app">
    <router-view v-if="isRouterAlice" />
  </div>
</template>

<script>
export default {
  name: "App",
  provide() {
    return {
      reload: this.reload,
    };
  },
  data() {
    return {
      isRouterAlice: true,
    };
  },
  methods: {
    // 刷新当前页面
    reload() {
      this.isRouterAlice = false;
      this.$nextTick(function () {
        this.isRouterAlice = true;
      });
    },
  },
};
</script>
<script>
export default {
  inject: ['reload'],
methods:{
    方法中调用this.reload()
  }
}
</script>

7.el-select联动选择框联动问题

使用el-select联动的时候,第一个选择框切换了选项第二个不会清空,如果给第二个v-model也清空的话会有选不上的问题,可能是element组件库的问题

//直接给第二个选择框添加一个vue强制刷新的实践$forceUpdate()
@change="$forceUpdate()"

8.axios表单提交 

开发的时候可能需要用到表单提交,可以使用下面方式

//引入 new FormData
const formData = new FormData();
//获取表单里的数据进行原型判断是否这个kev有的话添加到formData
  for (const key in this.dialogForm) {
      if (Object.hasOwnProperty.call(this.dialogForm, key)) {
      const element = this.dialogForm[key];
      formData.append(key, element||"");
     }
   }
//查看FormData的kev
  for (let key of formData.keys()) {
      console.log(key);
  }
//查看FormData的value
  for (let value of formData.values()) {
      console.log(value);
  }
//删除选项
formData.delete("")

9.ElementUI Message提示框问题

点击多次只显示一次 

this.$message.closeAll();

10.elementUI中Message组件首屏及刷新灰色弹窗问题 

elementUI中Message组件首屏及刷新灰色弹窗问题_$message灰色_小小鸟子的博客-CSDN博客

11.清除字符串中的,

str = str.replace(/,/g, "");

12.多元运算符的使用

var state = 2;
var select = (state == 1 ? "第一" : (state == 2 ? "第二":(state == 3 ? "第三" : "第四")))
console.log(select)

this.msgSuccess(res.extend.data=='新增成功'? this.$t('message')['新增成功']: (res.extend.data=='修改成功'?this.$t('message')['修改成功']: this.$t('message')['操作成功']))

13.element table title过长省略 

//全局方法挂载
import {renderHeader} from '@/utils/sxk'
Vue.prototype.renderHeader = renderHeader

export  function renderHeader(h, { column }) {
  return h(
    "div",
    {
      slot: "content",
      class: "table-header-flex",
    },
    [
      h(
        "el-tooltip",
        {
          props: {
            placement: "top",
          },
        },
        [
          h(
            "div",
            {
              slot: "content",
              style: {
                whiteSpace: "normal",
              },
            },
            column.label
          ),
          h(
            "span",
            {
              style: {
                whiteSpace: "normal",
                overflow: "hidden",
                "text-overflow": "ellipsis",
                "white-space": "nowrap",
                "max-width": "90%",
                display: "inline-block",
              },
            },
            column.label
          ),
        ]
      ),
    ]
  );
}

//模板使用
<el-table-column
 :render-header="renderHeader"
/>

14.element-ui table 整行单选颜色设置

::v-deep .current-row{
        td{
            background-color:rgba($Color29, 0.35) !important;
        }
}

15.element-ui table 隐藏滚动条

/deep/.el-table__body-wrapper {
  &::-webkit-scrollbar { // 整个滚动条
    width: 0; // 纵向滚动条的宽度
    background: rgba(213,215,220,0.3);
    border: none;
    height: 0;
  }
  &::-webkit-scrollbar-track { // 滚动条轨道
    border: none;
  }
}

16.flex布局问题

中间内容想居中忽略左右两边的影响

<div style="display: flex;">
    <div style="flex: 1;"></div>
    <div>中间内容自定义</div>
    <div style="flex: 1;"></div>
</div>

17.element-uI table 多选回显问题 

<el-table
    @selection-change="checkInTimeListChange"
    ref="table"
    :row-key="(row) => row.attId"
>
     <el-table-column
       type="selection"
       :reserve-selection="true"
        width="55"
        align="center"
      />
/>

//在调用回显的方法里调用 value2回显的Id数组 this.inspectionList table数据列表 faceDatabaseId筛选要回显的数据
this.$nextTick(() => {
   const inspectionIdList = value2.split(",").map((e) => e);
   this.inspectionList.forEach((row) => {
   if (inspectionIdList.includes(String(row.faceDatabaseId))) {
        this.$refs.multipleTable.toggleRowSelection(row, true);
      }
   });
});

18.一键截图

npm install html2canvas --save
import html2canvas from "html2canvas";
<div ref="imageTofile">//需要被截图的父元素添加ref
data(){
    return{
      saveInfo:{},
      imageTofile: null
    }
},
menthods:{
     toImage() {
      // if (props.steps.length === 0) {
      //   ElMessage.warning({
      //     message: "还没有添加步骤详情,无需上传截图信息",
      //   });
      //   return;
      // }
      // 手动创建一个 canvas 标签
      const canvas = document.createElement("canvas");
      // 获取父标签,意思是这个标签内的 DOM 元素生成图片
      // imageTofile是给截图范围内的父级元素自定义的ref名称
      let canvasBox = this.$refs.imageTofile;
      // 获取父级的宽高
      console.log(canvas);
      console.log(canvasBox);
      console.log(window.getComputedStyle);
      const width = parseInt(window.getComputedStyle(canvasBox).width);
      const height = parseInt(window.getComputedStyle(canvasBox).height);
      // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
      canvas.width = width * 2;
      canvas.height = height * 2;
      canvas.style.width = width + "px";
      canvas.style.height = height + "px";
      const context = canvas.getContext("2d");
      context.scale(2, 2);
      html2canvas(canvasBox, { allowTaint: true }).then((canvas) => {
        //document.body.appendChild(canvas)  页面布局会乱
        //转换base64
        // debugger;
        const capture = canvas.toDataURL("image/png");
        //下载浏览器弹出下载信息的属性
        this.saveInfo = {
          //导出文件格式自己定义,我这里用的是时间作为文件名
          download: this.getNowTime()+ `.png`,
          href: capture,
        };
        //下载,浏览器弹出下载文件提示
        this.downloadFile(this.saveInfo);

        //调用服务端保存接口
        // axios
        //   .post("/controller/testCases/uploadStempImg", {
        //     caseId: props.steps[0].caseId,
        //     projectId: props.steps[0].projectId,
        //     base64Img: capture,
        //   })
        //   .then((resp) => {
        //     if (resp["code"] === 2000) {
        //       ElMessage.success({
        //         message: resp["message"],
        //       });
        //       emit("flush");
        //     }
        //   });
      });
    },
    getNowTime() {
      const yy = new Date().getFullYear();
      const MM =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      const dd =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      const HH =
        new Date().getHours() < 10
          ? "0" + new Date().getHours()
          : new Date().getHours();
      const mm =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      const ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      return yy + MM + dd + "-" + HH + mm + ss;
    },
    downloadFile() {
      const element = document.createElement("a");
      element.style.display = "none";
      for (const key in this.saveInfo) {
        element.setAttribute(key, this.saveInfo[key]);
      }
      document.body.appendChild(element);
      element.click();
      setTimeout(() => {
        document.body.removeChild(element);
      }, 300);
    },
}

 出处如下,原文用vue3写的,我进行了修改,如侵联系删除

  Vue实现一键截屏功能_vue 截图_PhilipJ0303的博客-CSDN博客

 

Vue3 

1.app顶部固定其他滚动

.top{
    height: calc(100vh-98px)//减去的是顶部自身高度
    overflow-y: auto;
}

微信小程序

1.微信小程序使用fromData传递数据
GitHub - zlyboy/wx-formdata: 在小程序中使用formdata上传数据,可实现多文件上传

let formData = new FormData();
      formData.append("phone", this.data.myPhone);
      formData.append("orderTitle", this.data.title);
      formData.append("content", this.data.content);
      formData.append("userId", houseInfo.userId);
      formData.append("userHouseId", houseInfo.userHouseId);
      this.data.csimg.forEach(item => {
        formData.appendFile('img', item);
      });
      let data = formData.getData();
      wx.request({
        url: 'https://ai.hbzayun.com/communityManage/submitRepairOrder',
        header: {
          'content-type': data.contentType
        },
        data: data.buffer,
        method: 'POST'
      })

传入临时路径通过formData.appendFile('img', item);上传临时文件(binary)

2.微信小程序自适应顶部TOP

微信小程序自定义navigationBar顶部导航栏,兼容适配所有机型(附完整案例)_FaxMiao的博客-CSDN博客

微信原生小程序自定义顶部导航_微信小程序顶部栏_海龟先生plus的博客-CSDN博客

目前用的这个适配的小程序,效果不是特别好,需要自己调整,如果后期有更好的会替换掉。

3.微信小程序根据点击的位置给到对应的数据逻辑

<view wx:for="{{list}}" wx:key="item.recordId" data-index="{{index}}" bindtap="goDetails">

js
goDetails(e) {
    console.log(e.currentTarget.dataset.index);
    let details = this.data.list[e.currentTarget.dataset.index]
    console.log(details);
}

for循环出来的列表点击每项的时候,通过传入的index,去拿到网络请求获取的数组数据对应的index,从而判断拿到的是那一项的数据。

4.微信小程序this.setData修改属性带复杂索引问题

this.setData({[`judge[${current}]`]:true})

setData调用修改输出出现问题 | 微信开放社区

5.微信小程序点击跳转到PDF预览

 wx.downloadFile({
      url: 'http://**.*****.***/reshaiwai/demo.pdf',//要预览的PDF的地址
      success: function (res) {                           
        console.log(res);
        if (res.statusCode === 200) {//成功
          var Path = res.tempFilePath//返回的文件临时地址,用于后面打开本地预览所用
          wx.openDocument({
            filePath: Path,//要打开的文件路径
            success: function (res) {
              console.log('打开PDF成功');
            }
          })
        }
      },
      fail: function (res) {
        console.log(res); //失败
      }
  })

6.微信使用vant配置tabbar点击图标需要点击两次问题

onShow(e) {
     this.getTabBar().setData({isTabbar: "/pages/lookParkingSpace/index"})
  },
//isTabbar:定义切换的

6.微信小程序实现全选单选多选

<checkbox-group bindchange="selectAll">
  <checkbox value="all" checked="{{checkedAll}}"></checkbox> 一件全选
</checkbox-group>
<!-- 数据列表 -->
<view wx:for="{{dataList}}" wx:key="i">
  <view style="width:100%;height:60rpx;border:1px solid black;">
    <checkbox-group bindchange="checkboxChange" data-id="{{item.id}}">
      <checkbox value="{{item.id}}" style="float:left;" checked='{{item.checked}}'></checkbox>
    </checkbox-group> <text style="float:left">{{item.id}}</text>
  </view>
</view>
const app = getApp()
Page({
  data: {
    dataList: [{
        id: "17813566345",
        checked: false,
        num:1
      },
      {
        id: "27813566345",
        checked: false,
        num:2
      },
      {
        id: "37813566345",
        checked: false,
        num:3
      },
      {
        id: "47813566345",
        checked: false,
        num:4
      },
      {
        id: "57813566345",
        checked: false,
        num:5
      },
    ], // 数据列表
    checkedIds: [], // 选中的id列表,
    checkedAll: false
  },
  checkboxChange(e) {
    // 复选框change事件
    let id = e.detail.value[0];
    let checkedIds = this.data.checkedIds;
    if (id !== undefined && id !== '') {
      // 判断是否选中
      checkedIds.push(id);
    } else {
      // 过滤出选中的复选框
      checkedIds = checkedIds.filter(item => String(item) !== String(e.currentTarget.dataset.id));
    }
    if (checkedIds.length == this.data.dataList.length) {
      // 调整全选按钮状态
      this.setData({
        checkedIds: checkedIds,
        checkedAll: true
      })
    } else {
      this.setData({
        checkedIds: checkedIds,
        checkedAll: false
      })
    }
    console.log(this.data.checkedIds);
  },
  selectAll(e) {
    // 全选框
    if (e.detail.value[0] === "all") {
      console.log("全部选中");
      this.setData({
        checkedIds: this.data.dataList.map(item => item.id),
        dataList: this.data.dataList.map(item => {
          item.checked = true;
          return item;
        })
      })
    } else {
      // 直接清空列表
      console.log("清空");
      this.setData({
        checkedIds: [],
        dataList: this.data.dataList.map(item => {
          item.checked = false;
          return item;
        })
      });
    }
    console.log(this.data.checkedIds);
  }
})

7.微信小程序返回上一页携带参数

var pages = getCurrentPages(); // 获取页面栈
	var currPage = pages[pages.length - 1]; // 当前页面
	var prevPage = pages[pages.length - 2]; // 上一个页面
	prevPage.setData({
		// 要设置的值
		mydatas: {
			a:1,
			b:2
		} 
	})
	wx.navigateBack({ delta: 1})
//上一页onShow获取
onShow(){

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值