Article directory
-
- @[toc]
- Front-end public Js function library usage guide
- Start
-
-
- 1. Access common.js
- 2. Constructor exposure method reference
- 3. Initialization constructor
- Utility function
- network request
-
-
- 1. Request network request
- 2. setAuthData sets the interface call credentials
- WeChat JSSDK
-
-
- 1. wechatConfig WeChat Jssdk authentication method
- 2. shareConfig configures WeChat sharing
- 3. getSites Get user location information
- Page interaction
-
-
-
-
- showToast prompt box
- alert dialog box
- confirm confirmation box
- loading loading box
- hideLoading closes the loading box
- @[toc]
- Front-end public Js function library usage guide
- Start
-
-
- 1. Access common.js
- 2. Constructor exposure method reference
- 3. Initialization constructor
-
- Utility function
- network request
-
-
- 1. Request network request
- 2. setAuthData sets the interface call credentials
-
- WeChat JSSDK
-
-
- 1. wechatConfig WeChat Jssdk authentication method
- 2. shareConfig configures WeChat sharing
- 3. getSites Get user location information
-
- Page interaction
-
-
-
-
- showToast prompt box
- alert dialog box
- confirm confirmation box
- loading loading box
- hideLoading closes the loading box
-
-
-
Front-end public Js function library usage guide
This plug-in is based on the traditional project development method, integrates commonly used functions in the project development process, and encapsulates a unified ajax network request function for WeChat official jssdk also performs secondary encapsulation, and also provides commonly used page interaction components (no need to write html structure, automatically built by js). This plug-in is suitable for projects developed with traditional html + css + js. Using this plug-in can effectively improve development efficiency.
Getting started
1. Access common.js
Import directly with
script
tag
2. Constructor exposure method reference
The plug-in will automatically expose the constructor for use based on the current User Module Environment.
// commonjs module specification if (typeof module === "object" & amp; & amp; typeof module.exports === "object") {<!-- --> // commonjs module specification module.exports = commonFunction(); } else if (typeof define === "function" & amp; & amp; define.amd) {<!-- --> // AMD module specifications define(function (require, exports, module) {<!-- --> module.exports = commonFunction(); }); } else if (typeof define === "function" & amp; & amp; define.cmd) {<!-- --> //CMD module specification define(function (require, exports, module) {<!-- --> module.exports = commonFunction(); }); } else {<!-- --> //Module-less environment exposes commonFunction to the world root.common = commonFunction(); }
3. Initialization constructor
Constructor parameter description:
Parameter name | Purpose | Default value |
---|---|---|
baseUrl | Interface request base path | Empty string |
env | Application environment dev development environment prd production environment (vconsole debugging will be turned on in the development environment) |
dev |
requestLoading | Whether to display loading when sending a network request | true |
Example:
const commom = new commonFunction({<!-- --> baseUrl:"", env:"", requestLoading:"" })
Utility functions
method list
Function name | Purpose | Parameters | Return value |
---|---|---|---|
getEnvironment | Get the current application environment | None | Return the current application environmentwxapp:WeChat applet wxh5: WeChat h5 browser: Ordinary browser app: Mobile app application |
countDown | Calculate countdown | date: Pass in the timestamp or date string of the countdown end time |
object countdown information |
format | Convert timestamp to date string | timeStamp: time Stamp |
Date string such as: 2023-09-20 00:00:00 |
randomInt | Calculate a random integer in a specified range | min: minimum value max: maximum value |
Random integer |
randomFloat | Specify the range to calculate a random floating point number | min: minimum value max: Maximum value |
Random floating point number |
shuffle | Disrupt the order of the array | array: original array |
shuffled array |
groupBy | according to the object properties in the array Classify | arr: array object attr: attribute value for classification |
Classified data |
parseQueryString | Get the url parameters and combine them into objects to return | url: The url address where the parameters need to be obtained |
Page parameter object |
getFromData | Get and convert the data in the form into an object at one time | id:from the id of the form |
object:from the data in the form |
getQueryVariable | Query the specified url parameters | variable: parameter name |
Specified parameter value |
checkUrl | Determine the network protocol of the current page | isReplace: whether to automatically jump to https when the current page is http |
boolean: Whether it is https protocol |
Network request
Method list:
Function name | Purpose |
---|---|
request (Promise) |
Network request |
setAuthData | Set request header |
1. Request network request
This function is a secondary encapsulation based on the Jquery Ajax method. It is used to send requests and interact with the back-end server.
Example:
//Initialization constructor const common = new commonFunction() //send request common.request({<!-- --> url:"", //Interface address type:"", //Request method contentType: "", headers:{<!-- -->}, hsXhrFields:true, beforRequest:()=>{<!-- -->}, data:"" //Request parameters }).then(res=>{<!-- --> //Request successful }).catch(err=>{<!-- --> //Request failed })
Parameter Description:
Parameter name | Description | Default value |
---|---|---|
url (string) |
Backend interface address | None |
type (string) |
Request method | GET |
data (object) |
Request parameters | None |
contentType ( string) |
Data type | JSON |
headers (object) |
Request header | None |
hsXhrFields (boolean) |
Whether to carry cross-domain credentials | true |
beforRequest (function) |
Function executed before request is sent | Function |
(If the baseUrl parameter is specified when initializing the common instance object and the url parameter address does not end with http or https< /mark> will concatenate baseUrl and Url)
2. setAuthData sets the interface call credentials
During project development, you may encounter interface requests that require calling credentials (token) in the request header. The setAuthData method is to deal with this situation. By calling this method, you can go to the global interface. Add the desired fields to the request header and call it once for a single page.
Example:
const common = new commonFunction() //Add interface call credentials to the global request header common.setAuthData('base Token','value****************')
parameter list:
Parameter name | Description | Default value |
---|---|---|
key (string) |
The key of the interface calling certificate | None |
value (string) |
Value of interface call credentials | None |
WeChat JSSDK
The plug-in re-encapsulates WeChat weixin-js-sdk, aiming to improve WeChat development efficiency.
Method list:
Function name | Purpose |
---|---|
wechatConfig (Promise) |
WeChat jssdk authentication |
shareConfig (Promise) |
Configure WeChat sharing |
getSites (Promise) |
Get user location information |
1. wechatConfig WeChat Jssdk authentication method
This method is used for jssdk authentication operations. To call WeChat-related APIs such as WeChat sharing, obtaining location information, etc., the authentication method needs to be called first and the authentication can only be called after passing the authentication.
Example:
const common = new commonFunction() common.wechatConfig({<!-- --> debug: true, // Turn on debugging mode. The return values of all api calls will be alerted on the client side. If you want to view the incoming parameters, you can open it on the PC side. The parameter information will be printed out through the log, only on the PC side. will print. appId: '', // Required, the unique identifier of the official account timestamp: , // Required, timestamp for generating signature nonceStr: '', // Required, generate a random string for signature signature: '',// required, signature jsApiList: [] // Required, list of JS interfaces that need to be used }).then(res=>{<!-- --> //Authentication successful }).catch(err=>{<!-- --> //Authentication failed })
parameter list:
Parameter name | Description | Default value |
---|---|---|
configData (object) |
WeChat authentication parameters | None |
2. shareConfig configures WeChat sharing
Call this method to configure the title, thumbnail, description and other information of the shared message card in the WeChat application. (You need to call the WeChat authentication method first and the configuration can be successful after the authentication is passed)
Example:
const common = new commonFunction() const isPass = await common.wechatConfig(configData) //Determine whether the authentication is passed if(!isPass) return; common.shareConfig({<!-- --> title: window.title, //Share title link: location.href, //share address desc: "", //Share description imgUrl: "", //Share thumbnail success(res) {<!-- -->}, //Share success callback function cancel(can) {<!-- -->}, //Cancel sharing callback function fail(fail) {<!-- -->}, //Sharing failure callback function })
parameter list:
Parameter name | Description | Default value |
---|---|---|
options (object) |
WeChat sharing configuration information | {title: window.title,link: location.href,desc: "",imgUrl: "",success(res) {},cancel(can) {},fail(fail) {},} |
3. getSites obtains user location information
Return the current user location information (You need to call the WeChat authentication method first and the configuration can be successful after the authentication is passed)
Example:
const common = new commonFunction() const isPass = await common.wechatConfig(configData) //Determine whether the authentication is passed if(!isPass) return; common.getSites('wgs84').then(res=>{<!-- --> // Get success console.log(res) }).catch(err=>{<!-- --> // Failed to obtain console.log(err) }) //The default is the gps coordinates of wgs84. If you want to return the Mars coordinates directly for openLocation, you can pass in 'gcj02'
parameter list:
Parameter name | Description | Default value |
---|---|---|
type (String) |
Defaults to wgs84 gps coordinates , if you want to return the Mars coordinates used directly to openLocation , you can pass in gcj02 |
wgs84 |
Page interaction
method list
Function name | Purpose | Parameters |
---|---|---|
showToast | Show prompt text | text: prompt copy times: duration |
alert | Pop-up dialog box | option: configuration parameters callback: callback function after clicking the pop-up button |
confirm | Pop up confirmation dialog box | option: configuration parameters confirm: click Confirm callback function cancel: Click to cancel callback function |
loading | Display loading loading layer | title: Loading title |
hideLoading | Close the loading pop-up window | callback: callback function after closing |
close | Close pop-up box | type: pop-up window type (Legal values: alert, confirm, toast, loading) |
Call example:
showToast prompt box
common.showToast("Loading", 1000, () => {<!-- --> //Prompt box close callback console.log("toast close"); });
alert dialog box
common.alert({<!-- --> title:'Tips', content:'Confirmation box' },()=>{<!-- --> //Callback function after clicking confirmation, the pop-up window will be closed by default console.log('close alert') })
confirm confirmation box
common.confirm( {<!-- --> title: "Tips", content: "Do you confirm *****", hsCancel: true, // Whether to display the cancel button cancelText: "Forget it", //Cancel button copy hsConfirm: true, //Whether to display the confirmation button confirm: "confirm", }, () => {<!-- --> //Click to confirm console.log("confirm click"); }, () => {<!-- --> //Click to cancel console.log("cancel click"); } );
loading loading box
common.loading("Loading")
hideLoading closes the loading box
common.hideLoading()
Created Date: 2023.09.28
Developer: Weesion.Zhang(张文璇)
Email: [email protected]
Version: 3.0