Commonly used tool functions in Vue

foreword

This article records some commonly used tool functions in Vue projects. For the unified management of tool functions, these functions are uniformly placed srcin folders under the utilsdirectory.


1. Custom focus command

1. Method 1

The mouted cycle, ref+querySelector gets the input tag and calls focus()

2. Method 2

Custom directives (local) directives: fofo(inserted), defined and used on labels, v-fofo

3. Method three

Global custom instructions, recommended (high reusability). You can use it after importing it in main.js. The code is as follows (example):

import Vue from 'vue'

Vue.directive("fofo",{
  inserted(el) {
    // 判断拿到的元素名称
    if (el.nodeName === 'INPUT' || el.nodeName === 'TEXTAREA') {
      el.focus()
  	} else {
     // 尝试向内层获取一下
      el.querySelector('input').focus()
    }
  }
})
复制代码
复制代码

2. Anti-shake input box

1. Demand

When the user enters content in the input box, in order to get the user input content back to the server, it is necessary to monitor the input event of the input box, but when the value of the input box changes, an Ajax request is sent immediately, which will cause some inconsistencies. Necessary Ajax requests. When the user stops input and waits for a certain period of time, and then sends a request to the background, some unnecessary requests can be reduced.

2. Ideas

When the user starts to input, a timer is started. If the user does not input the content again after the timer expires, an Ajax request is sent to the background. If the user inputs again within the specified time, the last timer will be cleared and the timer will be re-timed.

3. Code implementation

Here is an example to demonstrate, after understanding the implementation principle, you can extract the code. The code is as follows (example):

<template>
	<div>
        <input type="text" v-model="kw" @input="inputFn"/>
    </div>
</template>
<script>
export default{
    data(){
        return{
            kw:'',
            timer:null
        }
    },
    methods:{
        inputFn(){
            clearTimeout(this.timer)
      		this.timer = setTimeout(() => {
                if(this.kw === '') return
                // 这里可以发送Ajax请求,根据用户输入的关键字拿到后台返回的搜索联想列表
                console.log(this.kw)
            }, 1000) // 当用户停止输入内容一秒后会执行定时器内的逻辑,如果一秒内又写了内容就会重新计时
      	}
   	}
}
</script>
复制代码
复制代码

3. Keyword highlighting

1. Demand

When the user searches for a keyword in the input box, the color of the keyword in the displayed association list will be changed, allowing the user to see the desired result more intuitively.

2. Ideas

Encapsulates a lightFnfunction that receives two arguments, the first is to receive the modified string, and the second is the keyword to match

3. Code demo

The code is as follows (example):

export const lightFn = (str, targetStr) => {
    // 忽略大小写且全局匹配
  const reg = new RegExp(targetStr, 'ig')
  return str.replace(reg, match => {
    return `<span style="color:red">${match}</span>`
  })
}
复制代码
复制代码

Fourth, format the time stored in the Excel table

1. Demand

Convert the time stored in the Excel table to be imported from the Excel format to the format at the time of storage.

2. Code demonstration

This code is quoted from Lan Yuxi , thanks to this big guy, here is the code~ The code is as follows (example):

export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}
复制代码
复制代码

Guess you like

Origin juejin.im/post/7005106444714377230