Summary of commonly used tool functions in Vue projects

Summary of commonly used tool functions in Vue projects

Preface

This article records some commonly used tool functions in Vue projects. For unified management of tool functions, these functions are uniformly placed in the utils folder under the src directory

1. Custom focus command

1. Method 1

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

2. Method 2

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

3. Method 3

Global custom instructions, recommended (high reusability). Just import it in main.js and use it. The code is as follows (example):

import Vue from 'vue'

Vue.directive("fofo",{
  inserted(el) {
    // Determine the name of the element obtained if (el.nodeName === 'INPUT' || el.nodeName === 'TEXTAREA') {
      el.focus()
  	} else {
     // Try to get the inner layer el.querySelector('input').focus()
    }
  }
})

2. Input box anti-shake

1. Demand

When the user enters content in the input box, in order to get the user's input content and feed it back to the server, it is necessary to monitor the input event of the input box. However, when the value of the input box changes, an Ajax request is sent immediately, which will cause some unnecessary Ajax requests. When the user stops typing and waits for a certain period of time, the request is sent to the background, which can reduce some unnecessary requests.

2. Ideas

When the user starts typing, a timer is started. If the user does not enter any content again after the timer ends, an Ajax request is sent to the background. If the user inputs again within the specified time, the previous timer will be cleared and the timer will be restarted.

3. Code implementation

Here is an example to demonstrate that after understanding the implementation principle, the code can be extracted. 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
                // Here you can send an Ajax request to get the search association list returned by the background according to the keywords entered by the user console.log(this.kw)
            }, 1000) // When the user stops inputting content for one second, the logic in the timer will be executed. If the user writes content again within one second, the timer will be restarted. }
   	}
}
</script>

3. Keyword highlighting

1. Demand

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

2. Ideas

Encapsulate a lightFn function, which receives two arguments, the first is the string to be modified, and the second is the keyword to be matched

3. Code Demonstration

The code is as follows (example):

export const lightFn = (str, targetStr) => {
    // Ignore case and match globally const reg = new RegExp(targetStr, 'ig')
  return str.replace(reg, match => {
    return `<span style="color:red">${match}</span>`
  })
}

IV. Format the time stored in Excel table

1. Demand

Convert the time stored in the Excel table to be imported from the Excel format to the format used for storage.

2. Code Demonstration

This code is quoted from Lan Yuxi. Thanks to this big guy, I will collect it here~ 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)
}

Summarize

This is the end of this article about the commonly used tool functions in Vue projects. For more relevant Vue commonly used tool functions, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the utility function examples in Vue

<<:  Nginx/Httpd reverse proxy tomcat configuration tutorial

>>:  Using System.Drawing.Common in Linux/Docker

Recommend

HTML+CSS merge table border sample code

When we add borders to table and td tags, double ...

WeChat applet implements SMS login in action

Table of contents 1. Interface effect preview 2.u...

Use image to submit the form instead of using button to submit the form

Copy code The code is as follows: <form method...

Two box models in web pages (W3C box model, IE box model)

There are two types of web page box models: 1: Sta...

How to switch directories efficiently in Linux

When it comes to switching directories under Linu...

MySQL transaction, isolation level and lock usage example analysis

This article uses examples to describe MySQL tran...

How to delete folders, files, and decompress commands on Linux servers

1. Delete folders Example: rm -rf /usr/java The /...

Detailed explanation of Tomcat core components and application architecture

Table of contents What is a web container? The Na...

JavaScript manual implementation of instanceof method

1. Usage of instanceof instanceof operator is use...

Solution to HTML2 canvas SVG not being recognized

There is a new feature that requires capturing a ...

Detailed explanation of MySQL database (based on Ubuntu 14.0.4 LTS 64 bit)

1. Composition and related concepts of MySQL data...

Detailed explanation of how Zabbix monitors the master-slave status of MySQL

After setting up the MySQL master-slave, you ofte...