In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to carry out modular processing in Mini Program, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to know about it.
The choice of ES6 and commonJS
First of all, in WeChat Mini Programs, both ES6 and commonJS modular syntax are supported. In traditional web projects, I am used to using ES6 modular syntax for development.
Initially, I also extracted all the common methods in Mini Program into a separate file and exported them using export or export default, and introduced them using import.
Pay attention
But! In the actual development, Mini Program's js file does not support the introduction of absolute path! This means that if you need to introduce a common method into your page, you must use.. / xxx/xxx.js, which will definitely deal a blow to your development enthusiasm when you introduce multiple modules on the same page.
Solution method
So how do we solve such a long introduction path? in web projects, we often use path aliases, such as webpack or resolve.alias in vite, to shorten the introduction path.
Alias: {"@ src": path.resolve ("src")
But in native WeChat Mini Programs, although Mini Program can be modified by some front-end engineering tools such as gulp or webpack, as an open source project, I hope its startup process does not require too much additional configuration. It is best to be able to implement it using native syntax.
Finally, I chose to add a require method to app.js to introduce the module, so when we introduce the module in the page, we only need to use the instance of app to import the module, so that we can use the relative path to the app.js file to import the file.
/ / app.jsApp ({require (path) {return path}})
Mode of use
/ / use app.js-based relative paths to import files, which avoids writing a lot of ".. /" const app = getApp () const upload = app.require ("lib/upload")
Of course, this is not particularly convenient, first of all, the code hints are not sound, using the above methods may not be in place for parameters or some return values, but the impact is not great. If I find out other better ways to implement it, then write an article to analyze it. Second, it is necessary to use the modular syntax of globally uniformly using commonJS, but this is not a problem.
Single page modularization
Mini Program does not provide a special modular approach, more commonly used is to extract some methods into a separate js file, and then introduce. The best way to avoid a page file code that is too long is to be componentized, but in Mini Program, it is really unpleasant to write components.
Mini Program components have their own life cycle, and must be defined in advance in the page json when introduced, because the component is hung on the shadow root node, if you want to share styles such as the global style of colorUI with the page, you need to write a separate configuration item styleIsolation. The overall development experience is more fragmented than vue.
Based on some of the above personal opinions, I seldom use components when writing Mini Program. If I need to pull away from wxml or js, I usually use the following methods.
Wxml modularization
In Mini Program, I usually use template template for extraction reuse, WeChat Mini Programs template documents, templates compared with the components extract only part of the page, does not include the extraction of the functional part.
The following is a template I extracted, which is a list item of an article, which has no separate functions, but the code is long and reused in many pages, so I extracted it. Write all the styles in the inline style so that the style is the same wherever it is introduced.
{{topic}} {{title}} {{content}} {{viewNum | | 0}} {{favorNum | | 0}} {{user.nickName}} {{createTime}}
When you use it in a page, you need to introduce it in advance. Since you can introduce multiple templates, you need to use the is attribute to declare which template to use. Data can be passed in through the data attribute. Here's an example where I deconstruct the traversed item and then assign it to it.
Of course, the template code that uses template for modular extraction can not contain too much functional logic, and the specific use still needs to be based on the business.
Js modularization
The most basic js modularization in Mini Program is to extract js files directly, such as some global common methods. The following shows the encapsulation of a global upload method.
/ / lib/upload.js// upload method module.exports = async function upload (path) {return await wx.cloud.uploadFile ({cloudPath: new Date () .getTime () + path.substring (path.lastIndexOf (".")), filePath: path })} / / pages/form/form.jsconst app = getApp () const upload = app.require ("lib/upload") Page ({async submit () {wx.showLoading ({mask: true) Title: "publishing"}) const imgList = [] for (let img of this.data.form.imgList) {const uploadRes = await upload (img) imgList.push (uploadRes.fileID)} / /. Other business codes}})
Of course, the above method is very convenient for the general method, but for some business code with high logical coupling with the page operation, it is not convenient to pull away.
In vue2, we can use mixin's method to modularize the code, in vue3 we can use hook's way to modularize the code, but there is no support for the above two in Mini Program. At first, I wanted to imitate the hook way of vue3 to encapsulate the page js, but the final effect was not ideal, so I chose to achieve modularization by imitating vue2 mixin.
The specific code has been implemented by other bloggers, so I used it directly. The specific code is as follows. If you don't know how to use mixin in vue, you can go to the official website to read the documentation. I won't introduce you too much here.
/ / mixin.js// saves the native Page function const originPage = Page// defines the properties / methods built into Mini Program const prop = ['data',' properties', 'options'] const methods = [' onLoad', 'onReady',' onShow', 'onHide',' onUnload', 'onPullDownRefresh',' onReachBottom', 'onShareAppMessage',' onPageScroll' 'onTabItemTap'] Page = (options) = > {if (Array.isArray (options.mixins)) {const mixins = options.mixins delete options.mixins mixins.forEach ((mixin) = > {for (let [key, value] of Object.entries (mixin)) {if (prop.includes (key)) {/ / mix attribute options [key] = {. Value ... options [key]}} else if (methods.includes (key)) {/ / mix the native method const originFunc = options [key] options [key] = function (... args) {value.call (this,... args) return originFunc & & originFunc.call (this) . args)} else {/ / mixed with the common method options = {... mixin,... options}})} originPage (options)}
The principle of implementation is to transform the Page () function in Mini Program. Every page of Mini Program is realized by calling the Page ({option}) method, and the data and declaration cycle functions and other methods related to the page are passed into the option parameters.
We add a mixin attribute to the parameter option of the Page method, which can be passed into an array, that is, each module to be mixed into, and the structure of each module is actually the same as the parameter option. We only need to merge all the mixed modules with the page's own option for a combination of parameters and methods to achieve the function of a mixin.
The method used is to introduce mixin.js into app.js now.
/ / app.jsrequire (". / mixins.js") App ({/ /... Other codes})
Then we write a regular page js, business code you do not have to look at, the main concern is that there is a mixins option in the properties of Page, and there is a topic module in the mixins array.
/ / pages/form/form.jsconst app = getApp () const upload = app.require ("lib/upload") const to = app.require ("lib/awaitTo") const db = wx.cloud.database () Page ({mixins: [require (". / mixins/topic")], data: {user: wx.getStorageSync ('user'), form: {title: "" Topic: ", content:", imgList: []}}, chooseImg () {wx.chooseImage ({count: 9-this.data.form.imgList.length) SizeType: ['original'], / / you can specify whether it is the original image or the compressed image By default, both have sourceType: ['album',' camera'] / / Select success: (res) = > {res.tempFilePaths = res.tempFilePaths if (this.data.form.imgList.length! = 0) {this.setData ({"form.imgList": this.data.form) from the album .imgList.concat (res.tempFilePaths)} else {this.setData ({"form.imgList": concat})}}) }, async delImg (e) {const index = e.currentTarget.dataset.index const temp = this.data.form.imgList temp.splice (index, 1) this.setData ({"form.imgList": temp})})
Because topic is full of related properties and methods, it can be extracted, so the js of the page will be more concise, if there is more code to extract according to their own judgment of the function, and then put it on the page for the mixin directory!
/ pages/form/mixin/topic.jsconst db = wx.cloud.database () module.exports = {data: {topic: {flag:false, list: []}, onLoad (options) {this.getTopic ()} Async getTopic () {const res = await db.collection ("topic") .get () this.setData ({"topic.list": res.data})}, clearTopic () {this.setData ({"form.topic": ""})} ToggleTopic (e) {console.log (e.currentTarget.dataset) const flag = e.currentTarget.dataset.flag this.setData ({"topic.flag": flag}),}
Pay attention
However, using mixin also has the same problem as in vue, that is, the source of variables and methods is difficult to trace, and the definition of variables in that location is more difficult to locate, so it is more dependent on the developer's development specifications and naming methods. If not, you can write a unique comment for each method.
Thank you for reading this article carefully. I hope the article "how to do Modularization in Mini Program" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.