国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Selection of ES6 and commonJS
Single page modularization
Home WeChat Applet Mini Program Development A brief analysis of how to elegantly implement modularization in small programs?

A brief analysis of how to elegantly implement modularization in small programs?

Dec 29, 2021 am 10:21 AM
Applets

How to modularize elegantly in small programs? This article will teach you how to elegantly modularize small programs. I hope it will be helpful to you!

A brief analysis of how to elegantly implement modularization in small programs?

This article talks about how to elegantly implement modular processing in WeChat mini programs. Through a condensed summary of some recent development experiences, we will explore some methods that can improve the efficiency of WeChat applet development and reduce mental burden.

Selection of ES6 and commonJS

First of all, both ES6 and commonJS are supported in the WeChat mini program. In traditional web projects, I am personally accustomed to using ES6 modular syntax for development.

At the beginning, I also extracted all the common methods in the mini program into separate files, and used export or export default to export, and used import Introduction.

Attention

But! In actual development, the js file of the mini program does not support the introduction of absolute paths ! This means that if you need to introduce a public method into your page, you must use the ../../../xxx/xxx.js method. When you introduce multiple When it comes to modules, this way of writing will definitely dampen your enthusiasm for development.

Solution

So how do we solve such a long import path? In web projects, we often use path aliases Methods, such as webpack or resolve.alias in vite to shorten the imported path.

alias: {"@src":path.resolve("src"),

But in the native WeChat applet, although some front-end engineering tools such as gulp or webpack can be used to make some modifications to the applet, as a I hope that the startup process of an open source project does not require too much additional configuration. It is best to use native syntax to implement it.

In the end, I chose to add a new require method in app.js to introduce the module. In this way, when introducing the module into the page, we only need to use the instance of the app to introduce the module. , so that you can use the relative path to the app.js file to import the file.

// app.js
App({
    require(path){
        return path
    }
})

Usage method

// 使用基于app.js的相對(duì)路徑來引入文件,這樣就避免了寫很多"../"
const app = getApp()
const upload = app.require("lib/upload")

Of course, this is not particularly convenient, first of allThe code prompt is not perfect. If you use the above method, the prompts for parameters or some return values ??may not be in place, but the impact will not be big. If I find other better implementation methods in the future, I will write an article to analyze it. Secondly, the modular syntax of commonJS must be used globally, but this is not a big problem.

Single page modularization

There is no special modularization method provided in the mini program. The more common method is to extract some methods into separate js files, and then Reintroduction. If you want to avoid a page file whose code is too long, the best way is to componentize it. However, in small programs, writing components is really unpleasant.

The mini program component has its own life cycle, and must be defined in advance in the page json when introduced. Since the component is hung on the shadow root node, if If you want to share styles with the page, such as the global style of colorUI, you also need to write the separate configuration item styleIsolation. The overall development experience is relatively fragmented compared to vue.

Based on some of the above personal opinions, I rarely use components when writing small programs. If I need to extract wxml or js, I usually use the following method.

wxml modularization

In small programs, I usually use template for abstraction and reuse, 微信小programTEMPLATEdoc Compared with components, templates only extract part of the page, and do not include the extraction of functional parts.

The following is a template I extracted. This is a list item of an article. It does not have any independent function, but the code is very longand is was reused in many pages, so I extracted it. Write the styles using inline styles, so that the same styles are introduced wherever they are introduced.

<!-- 文章列表項(xiàng) -->
<import src=&#39;./avatar&#39; />
<template name="post-item">
<view class="margin padding-sm bg-white radius flex shadow " style="position: relative;height: 350rpx;border-radius: 10rpx;">
        <!-- 背景蒙版 -->
        <view style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;border-radius: 10rpx;">
                <image style="filter:blur(2px) grayscale(80%) opacity(80%)" lazy-load="{{true}}" src="{{imgList[0]}}" mode="aspectFill"></image>
        </view>
        <view style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(30, 30, 30, 0.8);border-radius: 10rpx;">
        </view>

        <view style="z-index: 10;width: 100%;" class="text-white">
                <!-- 文章標(biāo)題 -->
                <view class="text-xl  ">
                        <text class="cu-tag margin-right-sm bg-color radius">{{topic}}</text>
                        <text class="text-bold">{{title}}</text>
                </view>
                <!-- 文章內(nèi)容 -->
                <view class="margin-top-xs text-sm text-cut">{{content}}</view>

                <view class="flex align-end justify-between margin-top">
                        <!-- 文章圖片 -->
                        <view class="flex align-center">
                                <view class="margin-xs" style="width: 120rpx;height: 120rpx;" wx:for="{{imgList}}" wx:key="{{index}}" wx:if="{{index < 3}}">
                                        <image class="radius" src="{{item}}" mode="aspectFill"></image>
                                </view>
                        </view>

                        <!-- 瀏覽量-點(diǎn)贊數(shù) -->
                        <view class="bg-color flex align-center text-white text-sm radius" style="padding: 4px 12px;">
                                <view class="cuIcon-attention "></view>
                                <view class="margin-left-xs">{{viewNum||0}}</view>
                                <view class="cuIcon-like margin-left"></view>
                                <view class="margin-left-xs">{{favorNum||0}}</view>
                        </view>
                </view>

                <!-- 發(fā)布時(shí)間 -->
                <view class="margin-top-xs flex align-center text-sm text-gray justify-between padding-lr-xs">
                        <view class="flex align-center">
                                <template is="avatar" data="{{size:45,avatarUrl:user.avatarUrl}}" />
                                <view class="margin-left-xs">{{user.nickName}}</view>
                        </view>

                        <view>{{createTime}}</view>
                </view>
        </view>

</view>
</template>

It needs to be introduced in advance when used in the page. Since multiple templates can be introduced, you need to use the

is attribute to declare which template is used. The data can be passed# The ##data attribute is passed in. The example here is that I deconstruct the traversed item and then assign it to it.

<!-- 某個(gè)頁面 -->
<import src=&#39;../../template/post-item&#39; />

<template data="{{...item}}" is="post-item" />
Of course, the template code that uses template for modularization and extraction cannot contain too much functional logic. The specific use still needs to be based on the business.

js modularity

在小程序中最基本的js模塊化就是直接抽離js文件,例如一些全局通用的方法,下面展示一個(gè)全局上傳方法的封裝

// lib/upload.js
// 上傳方法
module.exports = async function upload(path) {
	return await wx.cloud.uploadFile({
		cloudPath: new Date().getTime() + path.substring(path.lastIndexOf(".")),
		filePath: path,
	})
}
// pages/form/form.js
const app = getApp()
const upload = app.require("lib/upload")
Page({
async submit() {
    wx.showLoading({
            mask: true,
            title: "發(fā)布中"
    })
    const imgList = []
    for (let img of this.data.form.imgList) {
            const uploadRes = await upload(img)
            imgList.push(uploadRes.fileID)
    }
    // ...其他業(yè)務(wù)代碼
    }
})

當(dāng)然以上的辦法對(duì)于通用方法來說很方便,但是對(duì)于與 頁面操作的邏輯耦合性 很高的一些業(yè)務(wù)代碼,這樣子抽離并不方便。

在vue2中我們可以使用mixin的方法模塊化代碼,在vue3中我們可以使用hook的方式模塊化代碼,但是在小程序中并沒有以上兩者的支持,最初我想仿照 vue3的hook 方式進(jìn)行頁面js封裝改造,但最終實(shí)現(xiàn)的效果不理想,于是選擇了實(shí)現(xiàn)一個(gè)模仿vue2 mixin 的方法來實(shí)現(xiàn)模塊化。

具體代碼其他博主有實(shí)現(xiàn)過,因此我就直接拿來使用了,具體代碼如下。如果不了解vue中mixin的使用方法的可以自行去官網(wǎng)看文檔,這里不做過多介紹。

// mixin.js
// 保存原生的 Page 函數(shù)
const originPage = Page
// 定義小程序內(nèi)置的屬性/方法
const prop = [&#39;data&#39;, &#39;properties&#39;, &#39;options&#39;]
const methods = [&#39;onLoad&#39;, &#39;onReady&#39;, &#39;onShow&#39;, &#39;onHide&#39;, &#39;onUnload&#39;, &#39;onPullDownRefresh&#39;, &#39;onReachBottom&#39;, &#39;onShareAppMessage&#39;, &#39;onPageScroll&#39;, &#39;onTabItemTap&#39;]

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)) {
          // 混入屬性
          options[key] = {
            ...value,
            ...options[key]
          }
        } else if (methods.includes(key)) {
          // 混入原生方法
          const originFunc = options[key]
          options[key] = function (...args) {
            value.call(this, ...args)
            return originFunc && originFunc.call(this, ...args)
          }
        } else {
          // 混入普通方法
          options = {
            ...mixin,
            ...options
          }
        }
      }
    })
  }
  originPage(options)
}

實(shí)現(xiàn)的原理是改造小程序中的Page()函數(shù),小程序的每一個(gè)頁面都是通過調(diào)用Page({option})方法來實(shí)現(xiàn)的,在option參數(shù)中傳入頁面相關(guān)的data和聲明周期函數(shù)及其他方法。

我們通過在Page方法的參數(shù)option中增加一個(gè)mixin屬性,這個(gè)屬性可以傳入一個(gè)數(shù)組,數(shù)組即是每一個(gè)要混入的模塊,每一個(gè)模塊的結(jié)構(gòu)其實(shí)與參數(shù)option是一樣的,我們只需要將所有混入的模塊與頁面自身的option進(jìn)行一個(gè)參數(shù)和方法的合并就能實(shí)現(xiàn)一個(gè)mixin的功能。

使用的方法是現(xiàn)在app.js中引入mixin.js

// app.js
require("./mixins.js")
App({
// ...其他代碼
})

然后我們寫一個(gè)常規(guī)頁面的js,業(yè)務(wù)代碼大家不用看,主要關(guān)注Page的屬性中多了一個(gè)mixins選項(xiàng),而mixins數(shù)組中有一個(gè)topic模塊。

// pages/form/form.js
const 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(&#39;user&#39;),
		form: {
			title: "",
			topic: "",
			content: "",
			imgList: []
		}
	},
	chooseImg() {
		wx.chooseImage({
			count: 9 - this.data.form.imgList.length,
			sizeType: [&#39;original&#39;], //可以指定是原圖還是壓縮圖,默認(rèn)二者都有
			sourceType: [&#39;album&#39;, &#39;camera&#39;], //從相冊(cè)選擇
			success: (res) => {
				res.tempFilePaths = res.tempFilePaths
				if (this.data.form.imgList.length != 0) {
					this.setData({ "form.imgList": this.data.form.imgList.concat(res.tempFilePaths) })
				} else {
					this.setData({ "form.imgList": res.tempFilePaths })
				}
			}
		});
	},
	async delImg(e) {
		const index = e.currentTarget.dataset.index
		const temp = this.data.form.imgList
		temp.splice(index, 1)
		this.setData({ "form.imgList": temp })
	}
})

由于 topic 內(nèi)都是關(guān)聯(lián)性較強(qiáng)的屬性與方法,因此就可以抽離出來,這樣頁面的js就會(huì)更加精簡(jiǎn)啦,如果有更多的代碼就根據(jù)自己對(duì)于功能的判斷進(jìn)行抽離,然后放在頁面對(duì)于mixin目錄中即可!

// // pages/form/mixin/topic.js
const 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})
	},
}

注意點(diǎn)

但是使用mixin也有著與vue中同樣的問題就是變量及方法的來源不好追溯,變量是在那個(gè)位置定義的比較難以定位,這時(shí)就更加依賴開發(fā)者的開發(fā)規(guī)范以及命名方式了,再不濟(jì)也可以每一個(gè)方法寫一個(gè)獨(dú)有的注釋嘛~

【相關(guān)學(xué)習(xí)推薦:小程序開發(fā)教程

The above is the detailed content of A brief analysis of how to elegantly implement modularization in small programs?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: &lt;!--index.wxml--&gt;&l

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

Can small programs use react? Can small programs use react? Dec 29, 2022 am 11:06 AM

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Teach you how to use public account template messages in mini programs (with detailed ideas) Teach you how to use public account template messages in mini programs (with detailed ideas) Nov 04, 2022 pm 04:53 PM

This article brings you some related issues about WeChat mini programs. It mainly introduces how to use official account template messages in mini programs. Let’s take a look at them together. I hope it will be helpful to everyone.

Tutorial on writing a simple chat program in Python Tutorial on writing a simple chat program in Python May 08, 2023 pm 06:37 PM

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Geographical positioning and map display using PHP and mini-programs Geographical positioning and map display using PHP and mini-programs Jul 04, 2023 pm 04:01 PM

Geolocation positioning and map display of PHP and mini programs Geolocation positioning and map display have become one of the necessary functions in modern technology. With the popularity of mobile devices, people's demand for positioning and map display is also increasing. During the development process, PHP and applets are two common technology choices. This article will introduce you to the implementation method of geographical location positioning and map display in PHP and mini programs, and attach corresponding code examples. 1. Geolocation in PHP In PHP, we can use third-party geolocation

See all articles