


A brief analysis of the methods of customizing components in WeChat mini programs
How to customize components in WeChat mini program? The following article will introduce to you how to customize components in WeChat mini programs. I hope it will be helpful to you!
During the development process of WeChat applet, some page modules that may be used on multiple pages can be encapsulated into a component to improve development efficiency. Although we can introduce the entire component library such as weui, vant, etc., sometimes considering the package size limit of WeChat applet, it is usually more controllable to encapsulate it as a custom component.
And for some business modules, we can encapsulate them as components for reuse. This article mainly talks about the following two aspects:
- Declaration and use of components
- Component communication
Declaration and use of components
The bottom layer of the component system of the WeChat mini program is implemented through the Exparser component framework, which is built into the basic library of the mini program. All components in the mini program include built-in components and custom components. All managed by the Exparser organization.
Custom components include the following files just like writing pages:
- index.json
- index.wxml
- index.wxss
- index.js
- index.wxs
Take writing a tab
component as an example:
When writing a custom component, you need to set the component
field in the json
file to true
:
1 2 3 |
|
in js
In the file, the basic library provides two constructors, Page and Component. The page corresponding to Page is the page root component, and the Component corresponds to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
If you have friends who know Vue2, you will find this statement very familiar. .
When the mini program is started, the constructor will
write the properties, data, methods and other definition sections set by the developer into the component registry of Exparser. When this component is referenced by other components, it can create instances of custom components based on these registration information.
Template file wxml:
1 2 3 |
|
Style file:
1 |
|
To use external page components, you only need to introduce into the
json
1 2 3 4 5 6 |
|
When initializing the page, Exparser will create an instance of the page root component, and other components used will also respond by creating component instances (this is a recursive process):
The process of component creation There are roughly the following points:
According to the component registration information, create the
JS
object of the component node from the component prototype, that is, the component'sthis
;Copy the
data
in the component registration information as the component data, that is,this.data
;Combine this data with the component
WXML
, and create aShadow Tree
(node tree of the component), becauseShadow Tree
may reference other components, so this will recursively trigger the creation process of other components;Splice
ShadowTree
toComposed Tree
(finally spliced page node tree), and generate some cache data to optimize component update performance;trigger the
created
life cycle function of the component;If it is not the page root component, you need to set the attribute value of the component according to the attribute definition on the component node;
When the component instance is displayed on the page When up, the
attached
life cycle function of the component is triggered. If there are other components inShadow Tree
, their life cycle functions are also triggered one by one.
Component communication
Due to business responsibilities, we often need to split a large page into multiple components. Data communication is required between them.
For cross-generation component communication, global state management can be considered. Here we only discuss common parent-child component communication:
Method 1 WXML data binding
Used by the parent component to set data to the specified properties of the child component.
Child declaration properties
1 2 3 4 5 |
|
Parent component call:
1 |
|
Method 2 event
Use For child components to pass data to parent components, any data can be passed.
To dispatch events from a subcomponent, first bind the click event of the subcomponent in the wxml structure:
1 |
|
Then dispatch the event in the js file. The event name can be customized. The second parameter can pass the data object, and the third parameter is the event option.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Finally, listen in the parent component and use:
1 2 3 4 5 |
|
Method three selectComponent to get the component instance object
Pass# The ##selectComponent method can obtain the instance of the subcomponent and thus call the method of the subcomponent.
1 2 3 |
|
1 2 3 4 5 |
|
- ID选择器:
#the-id
(笔者只测试了这个,其他读者可自行测试) - class选择器(可以连续指定多个):
.a-class.another-class
- 子元素选择器:
.the-parent > .the-child
- 后代选择器:
.the-ancestor .the-descendant
- 跨自定义组件的后代选择器:
.the-ancestor >>> .the-descendant
- 多选择器的并集:
#a-node
,.some-other-nodes
方法四 url 参数通信
在电商/物流等微信小程序中,会存在这样的用户故事,有一个「下单页面A」和「货物信息页面B」
- 在「下单页面 A」填写基本信息,需要下钻到「详细页面B」填写详细信息的情况。比如一个寄快递下单页面,需要下钻到货物信息页面填写更详细的信息,然后返回上一个页面。
- 在「下单页面 A」下钻到「货物页面B」,需要回显「货物页面B」的数据。
微信小程序由一个 App()
实例和多个 Page()
组成。小程序框架以栈的方式维护页面(最多10个) 提供了以下 API 进行页面跳转,页面路由如下
wx.navigateTo(只能跳转位于栈内的页面)
wx.redirectTo(可跳转位于栈外的新页面,并替代当前页面)
wx.navigateBack(返回上一层页面,不能携带参数)
wx.switchTab(切换 Tab 页面,不支持 url 参数)
wx.reLaunch(小程序重启)
可以简单封装一个 jumpTo 跳转函数,并传递参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
jumpTo 辅助函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
在「下单页面A」传递数据:
1 2 3 4 5 6 |
|
在「货物信息页面B」获得 URL 参数:
1 |
|
url 参数获取辅助函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
参数过长怎么办?路由 api 不支持携带参数呢?
虽然微信小程序官方文档没有说明可以页面携带的参数有多长,但还是可能会有参数过长被截断的风险。
我们可以使用全局数据记录参数值,同时解决 url 参数过长和路由 api 不支持携带参数的问题。
1 2 3 4 5 6 7 |
|
更新跳转函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
url 参数获取辅助函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
辅助函数
1 2 3 |
|
按照这样的逻辑的话,是不是都不用区分是否是 isTabBar
页面了,全部页面都从 queryMap 中获取?这个问题目前后续探究再下结论,因为我目前还没试过从页面实例的 options
中拿到的值是缺少的。所以可以先保留读取 getCurrentPages
的值。
方法五 EventChannel 事件派发通信
前面我谈到从「当前页面A」传递数据到被打开的「页面B」可以通过 url 参数。那么想获取被打开页面传送到当前页面的数据要如何做呢?是否也可以通过 url 参数呢?
答案是可以的,前提是不需要保存「页面A」的状态。如果要保留「页面 A」的状态,就需要使用 navigateBack
返回上一页,而这个 api 是不支持携带 url 参数的。
这样时候可以使用 页面间事件通信通道 EventChannel。
pageA 页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
pageB 页面
1 2 3 4 5 6 7 8 9 10 11 |
|
会出现数据无法监听的情况吗?
小程序的栈不超过 10 层,如果当前「页面A」不是第 10 层,那么可以使用 navigateTo
跳转保留当前页面,跳转到「页面B」,这个时候「页面B」填写完毕后传递数据给「页面A」时,「页面A」是可以监听到数据的。
如果当前「页面A」已经是第10个页面,只能使用 redirectTo
跳转「PageB」页面。结果是当前「页面A」出栈,新「页面B」入栈。这个时候将「页面B」传递数据给「页面A」,调用 navigateBack
是无法回到目标「页面A」的,因此数据是无法正常被监听到。
不过我分析做过的小程序中,栈中很少有10层的情况,5 层的也很少。因为调用 wx.navigateBack
、wx.redirectTo
会关闭当前页面,调用 wx.switchTab
会关闭其他所有非 tabBar 页面。
所以很少会出现这样无法回到上一页面以监听到数据的情况,如果真出现这种情况,首先要考虑的不是数据的监听问题了,而是要保证如何能够返回上一页面。
比如在「PageA」页面中先调用 getCurrentPages
获取页面的数量,再把其他的页面删除,之后在跳转「PageB」页面,这样就避免「PageA」调用 wx.redirectTo
导致关闭「PageA」。但是官方是不推荐开发者手动更改页面栈的,需要慎重。
如果有读者遇到这种情况,并知道如何解决这种的话,麻烦告知下,感谢。
使用自定义的事件中心 EventBus
除了使用官方提供的 EventChannel 外,我们也可以自定义一个全局的 EventBus 事件中心。
因为这样更加灵活,不需要在调用 wx.navigateTo
等APi里传入参数,多平台的迁移性更强。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
在 PageA 页面监听:
1 |
|
在 PageB 页面派发
1 |
|
小结
本文主要讨论了微信小程序如何自定义组件,涉及两个方面:
- 组件的声明与使用
- 组件的通信
如果你使用的是 taro 的话,直接按照 react 的语法自定义组件就好。而其中的组件通信的话,因为 taro 最终也是会编译为微信小程序,所以 url 和 eventbus 的页面组件通信方式是适用的。后续会分析 vant-ui weapp 的一些组件源码,看看有赞是如何实践的。
感谢阅读,如有错误的地方请指出
【相关学习推荐:小程序开发教程】
The above is the detailed content of A brief analysis of the methods of customizing components in WeChat mini programs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to
