The applet references public js, it's a pity if you don't read it!!

Reprint: How WeChat Mini Programs Reference Public JS - Mobile Development - Billion Speed ​​Cloud

Thanks to the blogger for solving my problem and sharing it with everyone!! 

If you have any questions about reprinting, please private message me!

delete immediately

Blogger's original text

This article mainly introduces how to quote public js in WeChat applets, which has certain reference value, and friends who need it can refer to it. I hope you will gain a lot after reading this article. Let the editor take everyone to understand together.

Detailed explanation of WeChat applets referencing methods in public js

A small program page consists of four files, and the four files of a small program page have the same path and file name, so we can know that a small program page corresponds to a js file with the same name as the page. But when there are some public methods, we want to extract them into an independent public js file. How do we achieve it.

There is an app.js file in the root directory. The js file in this root directory can be easily called by getApp().

app.js

//app.js

App({
  globaData:'huangenai'
 })
//test.js
var app = getApp();
Page({
 onLoad: function () {
 console.log(app.globaData);
 } 
})

You can see it in the Console of the developer tool

Then when we extract some general public methods, there is a utils folder in the root directory (create it if there is no one), and util.js inside it (create it if there is no one). Here we can write the general methods here.

util.js

//正则判断
function Regular(str, reg) {
 if (reg.test(str))
  return true;
 return false;
}

//是否为中文
function IsChinese(str) {
 var reg = /^[\u0391-\uFFE5]+$/;
 return Regular(str, reg);
}
//去左右空格;
function trim(s){
  return s.replace(/(^\s*)|(\s*$)/g, "");
}

//最下面一定要加上你自定义的方法(作用:将模块接口暴露出来),否则会报错:util.trim is not a function;
module.exports = {
IsChinese: IsChinese,
trim: trim
}
//test.js

var util = require('../../utils/util.js');
Page({
  onLoad: function () {
  console.log("判断是否为中文:"+util.IsChinese('测试'));
  console.log("去除左右空格:" + util.trim(s));
  }
})

You can see it in the Console of the developer tool

Note that in the Regular() method in util.js, we cannot call util.Regular() like this, because we did not use module.exports to expose the module interface

If you call it directly, you will get an error like this

thirdScriptError util.Regular is not a function;at "pages/test/test" page lifeCycleMethod onLoad function TypeError: util.Regular is not a function

Thank you for reading this article carefully. I hope that Xiaobian’s sharing of how to quote public js content in WeChat applets will be helpful to everyone.

Guess you like

Origin blog.csdn.net/m0_53016870/article/details/126820637