preface
This paper mainly from date, array, object, AXIos,promise and character judgment these aspects of the work of some commonly used functions encapsulated, indeed can be directly referenced in the project, improve the efficiency of development.
Date of 1.
Date in the background management system is still used a lot, generally as a dimension of data storage and management, so it will involve a lot of date processing
1.1 Date formatting for element-UI
DatePicker Date picker gets the Date object by default, but we need to use yyyY-MM-DD in the background, so we need to convert it
Method 1: Convert the value to DD-MM-YYYY HH: MM :ss
export const dateReurn1=(date1)=>{
date1.toLocaleString("en-US", { hour12: false }).replace(/\b\d\b/g, '0$&').replace(new RegExp('/','gm'),'-')
}
Copy the code
Method 2:
The value format property is provided from the 2.x version of element-UI, which allows you to directly set the value returned by the selector
1.2 Obtaining the current time YYYY-MM-DD HH: MM :ss
If you don’t reach 10, fill in 0
export default const obtainDate=()=>{ let date = new Date(); let year = date.getFullYear(); let month = date.getMonth() + 1; let day=date.getDate(); let hours=date.getHours(); let minu=date.getMinutes(); let second=date.getSeconds(); / / determine whether full 10 let arr = [month, day, hours, minu, second]; arr.forEach(item=>{ item< 10?" 0"+item:item; }) console.log(year+'-'+arr[0]+'-'+arr[1]+' '+arr[2]+':'+arr[3]+':'+arr[4]) }Copy the code
An array of 2.
2.1 Check whether it is an array
export default const judgeArr=(arr)=>{ if(Array.isArray(arr)){ return true; }}Copy the code
2.2 Array de-set method
1. The common use of loops and indexOf(ES5 array method, can return the position of the first occurrence of the value in the array) is not detailed here, here is a set implementation using ES6.
2. A set is a new data structure, similar to an array, but with the feature that all elements are unique.
3. Set common operations you can refer to the following
4. Set deduplication code
Export const changeReArr=(arr)=>{return array. from(new Set([1,2,2,3,5,4,5]))// convert [1,2,2,3,5,4,5] to Set data using Array Export const changeReArr=(arr)=>{return [...new set ([1,2,2,3,5,4,5])] The extension operator redefines an array by iterating over the values in a set... Is used for... Of traversal}Copy the code
Array.from can convert an array-like object with lenght attributes to an Array, and can also convert a traversable object such as a string to an Array. It takes 2 arguments, converts the object and the callback function,… And array. from are both ES6 methods
2.3 Pure array sort
So there’s a lot of bubbling and selection, so LET me write it here using sort
Export const orderArr=(arr)=>{arr.sort((a,b)=>{return a-b // return -(a-b)})}Copy the code
2.4 Sorting array objects
export const orderArr=(arr)=>{ arr.sort((a,b)=>{ let value1 = a[property]; let value2 = b[property]; return value1 - value2; // the sort method takes a function as an argument. Here we have a nested layer of functions that take object property names with //. The rest of the code is the same as normal})}Copy the code
2.5 Array “short circuit “every and some
Array short-circuiting is a name I coined myself, because there is a general requirement that one or all of the elements in an array should return true
Export const allTrueArr=(arrs)=>{arr. Every ((arr)=>{return arr>20; Export default const OneTrueArr=(arrs)=>{arr.some((arr)=>{arr.some((arr)=>{ return arr>20; Return false if none of the items in the array are satisfied, and true if none of the items are satisfied, terminating the loop})}Copy the code
Above two scenarios and | | and & & short circuit operation is very similar, so I took a name is a short circuit calculation, the two cases, of course, can traverse to judge each item and then using break and return false to end loops and function.
3. The object
3.1 Object Traversal
Export const traverseObj=(obj)=>{for(let variable in obj){// for... If (obj.hasownProperty (variable)){console.log(variable,obj[variable])}}}Copy the code
3.2 Data Attributes of objects
1. Object attribute classification: data attribute and accessor attribute;
2. Data properties: a position containing data values, which can be read and written, and contains four features:
Enumerable: the writable property is returned via a for-in loop, exercising different control systems, which allows you to delete the property and modify the property via delete. The default is true, and the property can be modified as an accessor property. Indicates whether the value of an attribute can be modified. Value: Indicates the data value that contains the attribute. The default value is undefinedCopy the code
3. Modify the default properties of data attributes, using Object.defineProperty()
Export const modifyObjAttr=()=>{let person={name:' zhang3 ',age:30}; DefineProperty (person,'name',{writable:false, value:' li ', Enumerable :false})} Enumerable: disables any additional information, and controls no additional information.Copy the code
3.3 Accessor properties of objects
1. Four features of accessor properties:
Enumerable: The property can be returned via a for-in loop, and the default is false. The default is different, and the property can be deleted without any additional information. Function called when a property is read, default is undefined Set: Function called when a property is written, default is undefinedCopy the code
2. Definition: Accessor properties can only be defined by the object.defineProperty () method
Export const defineObjAccess=()=>{let personAccess={_name:' zhang3 ',//_ Object.defineProperty(personAccess,'name',{ get:function(){ return this._name; }, set:function(newName){ if(newName! ==this._name){ this._name=newName; this.editor++; }} // If only get method is defined, change object can only read})}Copy the code
The core of the reactive principle in VUE is to change data by hijacking the getters and setter properties of data via defineProperty
4.axios
4.1 Axios get method
export const getAjax= function (getUrl,getAjaxData) { return axios.get(getUrl, { params: { 'getAjaxDataObj1': Obj1,//obj1 is an attribute of getAjaxData 'getAjaxDataObj2': getajaxdata.obj2}})}Copy the code
4.2 Axios post method
export const postAjax= function (getUrl,postAjaxData) { return axios.get(postUrl, { 'postAjaxDataObj1': Postajaxdata.obj1,//obj1 is an attribute of postAjaxData 'postAjaxDataObj2': postaJAXData.obj2})}Copy the code
4.3 Axios interceptor
There are two types of interceptors: request interceptor and response interceptor. Request interception is usually configured with the corresponding request header information (applicable to common request methods, although ajax GET method does not have a request header, but axios encapsulation), and the response is usually intercepted by Reponse. If the return result is [], it can be converted to 0
1. Request interception: Put the current city information into the request header
axios.interceptors.request.use(config => {
config.headers.cityCode = window.sessionStorage.cityCode //jsCookie.get('cityCode')
return config
},
Copy the code
2. Response interception: Process the results of rePONse
axios.interceptors.response.use((response) =>{ let data = response.data if(response.request.responseType === 'arraybuffer'&&! data.length){ reponse.date=0 } })Copy the code
5.promise
Promise is an easy-to-reuse asynchronous task management mechanism that encapsulates future values, addressing hell-callback and controlling the order of asynchrony
5.1 Application Method 1
export const promiseDemo=()=>{ new Promise((resolve,reject)=>{ resolve(()=>{ let a=1; return ++a; }). Then ((data) = > {the console. The log (data) / / the data value for + + a}). The catch (() = > {/ / error executing this})})}Copy the code
5.2 Application Method 2
Export const promiseDemo=()=>{promise.resolve ([1,2,3]). Then ((data)=>{// directly initialize a Promise and execute the resolve method Console. log(data)//data values are [1,2,3]})}Copy the code
6. Text box judgment
6.1 All numbers
Method 1 (easiest):
export default const judgeNum1=(num1)=>{ if(typeof num1==number){ return true; }else{ return false; }}Copy the code
Method 2: isNaN
export default const judgeNum1=(num1)=>{
if(!isNaN(num1)){
return true;
}else{
return false;
}
}
Copy the code
Note: when num1 is [] (an empty array), “” (an empty string), and null are converted to numeric type 0 during the procedure, so false is returned. Therefore, the above special cases can be typeof excluded.
Method three: re
export default const judgeNum1=(num1)=>{ let reg=/^[0-9]*$/ if(! Reg.test (num1)){console.log('num1 is 0-9')}}Copy the code
6.2 The value can be numbers or letters only
This uses the re judgment to define a re :let reg=/^[0-9a-za-z]*$/g
6.3 The value can contain only digits, letters, and commas
Let reg=/^[0-9a-za-z,]*$/g
6.4 Check whether the number of digits to be entered is less than 16
Use the length attribute of the string directly
Export default const judgeNum1=(num1)=>{if(num1.length>16){console.log('num1 exceeds 16 bits ')}}Copy the code
The end of the
I’m glad you can still see it, because these are classes that you probably don’t need right now, but you can save for now. We can communicate with each other and use it directly for the next project development. Now the project is in a rush in March, which can really improve the development efficiency! Happy New Year to you all. If you feel that the writing can also please like, to meet some of my sense of achievement, thank you!