最近的移动端项目用到的一些不常用的小技巧:

直接上干货

  • vue-cli3 中webpackServer代理

首先,.env.development文件设置
VUE_APP_baseApi = /api
其次,vue.config.js文件设置

devServer: {
  proxy: {
      '/api': {
          target: 'http://xxx/api',
          changeOrigin: true,
          ws: true,
          pathRewrite: {
            '^/api': ''
          }
      }
  }
}
  • 日期格式化(yyyy-mm-dd hh:mm)
dateFormatter(val) {
    const YYYY = val.getFullYear()
    const MM = val.getMonth() + 1 < 10 ? "0" + (val.getMonth() + 1) : val.getMonth() + 1;
    const DD = val.getDate() < 10 ? "0" + val.getDate() : val.getDate();

    const hh = val.getHours() < 10 ? "0" + val.getHours() : val.getHours();
    const mm = val.getMinutes() < 10 ? "0" + val.getMinutes() : val.getMinutes();
    return `${YYYY}-${MM}-${DD} ${hh}:${mm}:`
  },
  • 日期相减计算(y年m月d日h时m分)
getRemainderTime(val) {
    let runTime = null
    runTime = parseInt(val) / 1000;
    let year = Math.floor(runTime / 86400 / 365);
    runTime = runTime % (86400 * 365);
    let month = Math.floor(runTime / 86400 / 30);
    runTime = runTime % (86400 * 30);
    let day = Math.floor(runTime / 86400);
    runTime = runTime % 86400;
    let hour = Math.floor(runTime / 3600);
    runTime = runTime % 3600;
    let minute = Math.floor(runTime / 60);
    runTime = runTime % 60;
    let second = runTime;
    // console.log(year,month,day,hour,minute,second);
    this.countHour = parseInt(val) / 1000 / 3600
    return `${year?year+'年':''}${month?month+'月':''}${day?day+'天':''}${hour?hour+'小时':''}${minute?minute+'分钟':''}`
  },
  • 音频流转mp3格式
convertToMp3(wavDataView) {
    // 获取wav头信息
    const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息,毕竟有对应的config配置
    const {
      channels,
      sampleRate
    } = wav;
    const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
    // 获取左右通道数据
    const result = recorder.getChannelData()
    const buffer = [];

    const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
    const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
    const remaining = leftData.length + (rightData ? rightData.length : 0);

    const maxSamples = 1152;
    for (let i = 0; i < remaining; i += maxSamples) {
      const left = leftData.subarray(i, i + maxSamples);
      let right = null;
      let mp3buf = null;

      if (channels === 2) {
        right = rightData.subarray(i, i + maxSamples);
        mp3buf = mp3enc.encodeBuffer(left, right);
      } else {
        mp3buf = mp3enc.encodeBuffer(left);
      }

      if (mp3buf.length > 0) {
        buffer.push(mp3buf);
      }
    }

    const enc = mp3enc.flush();

    if (enc.length > 0) {
      buffer.push(enc);
    }

    let blob = new Blob(buffer, {
      type: 'audio/mp3'
    })
    return blob
  },
  • vue bus

main.js

const bus = new Vue()
Vue.prototype.bus = bus

a.vue

this.bus.$emit("onlineType", ...arg)

b.vue

this.bus.$on('useCardTime', (res) => {
    console.log(res)
})
  • 重置表单数据

this.$options除了获取data,还可以获取组件中实例方法

retset() {
        this.form = this.$options.data().form;
}
  • elementui 错误message重复触发时引入(重置message,防止重复点击重复弹出message弹框 )
import { Message } from 'element-ui'
const showMessage = Symbol('showMessage')
let messageInstance = null
class DoneMessage {
  [showMessage] (type, options, single) {
    if (messageInstance && single) {
      messageInstance.close()
    }
    messageInstance = Message[type](options)
  }
  info (options, single = true) {
    this[showMessage]('info', options, single)
  }
  warning (options, single = true) {
    this[showMessage]('warning', options, single)
  }
  error (options, single = true) {
    this[showMessage]('error', options, single)
  }
  success (options, single = true) {
    this[showMessage]('success', options, single)
  }
}
export const message = new DoneMessage()
  • key值设置

可能场景:同一个table组件中根据切换角色刷新组件表头及组件内容。
不设置key值会导致即使你使用v-if切换column显示开关仍会错误显示不应该出现的表头项。
官网解释Vue 会尽可能高效地渲染元素,通常会复用已有元素而不是从头开始渲染。,通过设置不同的key值可有效防止此类情况(循环中不应设置index)

  • 父子通讯
//父组件的点击事件
<button  @click="fuSublime">提交事件</button>

//调用自组件,子组件注册一个ref="searchForm"
<zi @fuSublime='sublime' ref="searchForm" ></zi>

    // 点击父组件的事件 
    fuSublime(){
       //引用ref,点击子组件的ziSublime()
      this.$refs.searchForm.ziSublime()
    },
    // 接收子组件返回的值 
    sublime(e){
      if(e){
        //返回的是true
        this.addDialogVisible = false
      }
    }, 
 methods: {
    ziSublime() {
      // 自组件的点击事件
      this.$refs['searchForm'].validate((valid) => {
        if (valid) {
        //返回父组件
          this.$emit('fuSublime', valid)
        } else {
          return false
        }
      })
    }
  }
  • 重写push方法,解决相同路径跳转报错
const originalPush = Router.prototype.push

Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

AlexKing9527
12 声望2 粉丝