vue的开发问题

320 阅读1分钟

1、vue-element-admin中路由懒加载:

  {
    path: '/a-order',
    component: Layout,
    redirect: '/a-order/a-index',
    name: 'a-order',
    meta: { title: '订单管理', icon: 'el-icon-s-order', roles: ['admin'] },
    children: [
      {
        path: 'a-index',
        name: 'a-order-index',
        component: (resolve) => require(['@/views/a/index'], resolve),
        meta: { title: '列表', icon: '', roles: ['admin'] }
      }
    ]
  },
}

2、自定义地图插件: leaflet.js 【 npm i leaflet 】
(1)、utils目录中创建map.js

import 'leaflet/dist/leaflet.css'
import $L from 'leaflet'

const createMap = (divId, options) => {
  const map = $L.map(divId, { crs: $L.CRS.Simple, ...options })
  return map
}

/**
 * CRS.Simple坐标系采用[y, x]来代替[x, y],同样在Leaflet中也采用[lat, lng]来代替[lng, lat]
 */
const xyToLatlng = (x, y) => {
  if ($L.Util.isArray(x)) {
    return $L.latLng(x[1], x[0])
  }
  return $L.latLng(y, x)
}

const createImageOverlay = async(map, options = {}) => {
  const { src, x, y } = options
  if (!src) return false
  const s = xyToLatlng(-100, -100)
  const e = xyToLatlng(x + 100, y + 100)
  const bounds = [
    [0, 0],
    [y, x]
  ]
  const image = $L.imageOverlay(options.src, bounds)
  image.addTo(map)
  map.setMaxBounds([s, e])
  map.fitBounds(bounds)
  return image
}

export default {
  createMap,
  createImageOverlay,
  xyToLatlng,
  L: $L
}

(2)组件界面,解决鼠标绘制矩形

<template>
  <div id="map-cotent" class="map-cotent" ></div>
</template>
<script>
import mapFun from '@/utils/map'
let rectangle
let tmprec
const latlngs = []
export default {
  name: 'MapEdit',
  data() {
    return {
      mapImg: 'xxxxx',
      imgWidth: 110,
      imgHeight: 110
    }
  },
  mounted() {
     this.map = mapFun.createMap('map-cotent', {
       minZoom: -1,
       maxZoom: 2,
       zoomControl: true,
       attributionControl: false
     })
     mapFun.createImageOverlay(that.map, {
       src: that.mapImg,
       x: imgWidth,
       y: imgHeight
     })
     this.map.on('mousedown', this.downEvent) // 点击地图
     this.map.on('mouseup', this.upEvent)
  },
  methods: {
    downEvent(e) {
      tmprec && tmprec.remove()
      latlngs[0] = [e.latlng.lat, e.latlng.lng]
      this.map.dragging.disable()
      this.map.on('mousemove', this.moveEvent)
    },
    upEvent(e) {
      // 矩形绘制完成,移除临时矩形,并停止监听鼠标移动事件
      tmprec && tmprec.remove()
      this.map.off('mousemove')
      // 右下角坐标
      latlngs[1] = [e.latlng.lat, e.latlng.lng]
      rectangle = mapFun.L.rectangle(latlngs, {
        color: '#1890ff',
        fillOpacity: 0.1,
        weight: 2
      })
      rectangle.addTo(this.map)
      this.map.dragging.enable()
    },
    moveEvent(e) {
      latlngs[1] = [e.latlng.lat, e.latlng.lng]
      // 删除临时矩形
      tmprec && tmprec.remove()
      // 添加临时矩形
      tmprec = mapFun.L.rectangle(latlngs, { dashArray: 5 }).addTo(this.map)
    }
  }
}
</script>

3、canvas画图插件:konva.js
4、运用js修改scss中的变量

<template>
<div />
</template>
<script>
export default {
  name: 'ff',
  mounted() {
    document.getElementsByTagName('body')[0].style.setProperty('--widthBox', '130px')
  }
}
</script>
<style lang="scss" scoped>
  $widthBox: var(--widthBox);
</style>

4、el-time-select在el-form-item中Dom不更新问题

<el-form-item prop="pmTimes_e" :key="form.pmTimes_e"  >
     <el-time-select
         v-model="form.pmTimes_e"
         style="width: 100%"
         :picker-options="{
          start: '00:00',
          step: '00:10',
          end: '19:00',
         }"
         placeholder="结束" />
</el-form-item>
                  
// 其中 :key="form.pmTimes_e" 是解决问题的关键代码                 

5、# Lodash的正确用法之debounce和throttle

<el-input
  v-model="searchVal"
  :placeholder="请输入关键字搜索"
  @input="searchMethod"
>
  <i slot="suffix" class="el-icon-search" />
</el-input>


// 一定是这种使用方式才有效,不要使用箭头函数,不然内部获取不到 this
searchMethod: debounce(function (e) {
      console.log('Debounced Event:', e);
      const k = e.target.value || ''
      this.getListFun(k)
}, 200)

6、axios最新版本中,配置config额外参数
如下中needToken是额外配置,在service.interceptors.request.use(请求拦截器)中是获取不到的。

export function logout () {
  return request({
    url: 'member/logout',
    method: Method.POST,
    needToken: true
  })
}

解决方案如下:

// 路径:/node_modules/axios/lib/core/mergeConfig.js
// 在defaultToConfig2Keys中添加needToken
// 如果生产环境是引入的,一定要收到找到当前位置,否则参数是接不到的

var defaultToConfig2Keys = [
    'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
    'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
    'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
    'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
    'httpsAgent', 'cancelToken', 'socketPath', 'needToken'
  ];

7、在生产环境中,禁用console.log

let jsPlugin = [
  new UglifyJsPlugin({
    uglifyOptions: {
      // 删除注释
      output: {
        comments: true
      },
      compress: {
        drop_console: false, // 删除所有调式带有console的
        drop_debugger: false,
        pure_funcs: [] // 删除console.log
      }
    }
  })
];

8、报Cannot find module 'vue-template-compiler'的问题

// 第一步安装
npm install vue-template-compiler
// 第二步运行,各个项目可能不同
npm run serve 
// 如果提示下面的异常
vue@2.6.12 (/vue.runtime.common.js)
- vue-template-compiler@2.7.8 (/Users/node_modules/vue-template-compiler/package.json)

This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader@>=10.0, simply update vue-template-compiler.
If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.

// 第三步安装正确的vue-template-compiler,2.6.12 这个版本 对应上面提示的错误(vue@2.6.12)
npm install vue-template-compiler@2.6.12

// 第四步运行,这时应该没有问题了
npm run serve

**9、打字组件 # Typed.js
官网地址

10、图片加载
      const xhr = new XMLHttpRequest();
      // 支持相对路径,例如:./images/a.jpg
      xhr.open("GET", url , true);
      xhr.send();
      xhr.addEventListener("load", function () {
        i++;
        loadok(i);
      })
      xhr.addEventListener("error", function (w) {
        i++;
        loadok(i);
        console.warn(w);
      })
11、微信小程序获取参数[小程序码以及普通码]
const getQuery = function (p) {
   p = p || '';
   const u = decodeURIComponent(p);
   const g = u.split('&') || [];
   const r = {};
   for(let i = 0; i < g.length; i++) {
       const p = (g[i] || '').split('=');
       if(p[0] && p[1]) {
           r[`${p[0]}`] = p[1];
       }
   }
   return r;
}