In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how to customize the components in WeChat Mini Programs. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
In the development process of WeChat Mini Programs, for some page modules that may be used in multiple pages, it can be encapsulated into a component to improve development efficiency. Although we can introduce the entire component library such as weui, vant, etc., but sometimes consider WeChat Mini Programs's package size limit, usually encapsulated as custom components are more controllable.
And for some business modules, we can encapsulate them into component reuse. This paper mainly deals with the following two aspects:
Declaration and use of components
Component communication
Declaration and use of components
The bottom layer of WeChat Mini Programs's component system is implemented through the Exparser component framework, which is built into the basic library of Mini Program. All components in Mini Program, including built-in components and custom components, are managed by Exparser.
The custom component contains the following files as well as 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 to true in the json file:
{"component": true}
In the js 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:
Component ({options: {/ / component configuration addGlobalClass: true, / / specifies that all data fields starting with _ are pure data fields / / pure data fields are data fields that are not used for interface rendering Can be used to improve the performance of page updates pureDataPattern: / ^ _ /, multipleSlots: true / / enable multi-slot support in the options when components are defined}, properties: {vtabs: {type: Array, value: []},}, data: {currentView: 0,} Observers: {/ / Monitoring activeTab: function (activeTab) {this.scrollTabBar (activeTab) }, relations: {/ / the associated child / parent component'.. / vtabs-content/index': {type: 'child', / / the associated target node should be the child node linked: function (target) {this.calcVtabsCotentHeight (target) }, unlinked: function (target) {delete this.data._ contentHeight [target.data.tabIndex] }}, lifetimes: {/ / component declaration cycle created: function () {/ / component instance has just been created}, attached: function () {/ / execute when the component instance enters the page node tree Detached: function () {/ / execute} when the component instance is removed from the page node tree,}, methods: {/ / component method calcVtabsCotentHeight (target) {}})
If you have a small partner who knows Vue2, you will find this statement familiar.
When Mini Program starts, the constructor will define segments such as properties, data, methods, etc. set by the developer.
Write to the component registry of Exparser. When this component is referenced by other components, you can create an instance of the custom component based on this registration information.
Template file wxml:
Style file:
.vtabs {}
External page components only need to be introduced in the page's json file
{"navigationBarTitleText": "Commodity Classification", "usingComponents": {"vtabs": ".. / components/vtabs",}}
When the page is initialized, Exparser creates an instance of the root component of the page, and other components used respond to the creation of component instances (which is a recursive process):
The process of creating a component has the following main points:
According to the component registration information, the JS object of the component node, that is, the this of the component, is created from the component prototype.
Copy a copy of the data in the component registration information as component data, namely this.data
Combine this data with the component WXML to create a Shadow Tree (the node tree of the component), which recursively triggers the creation process of other components because other components may be referenced in the Shadow Tree
Splice the ShadowTree into the Composed Tree (the final spliced page node tree) and generate some cached data to optimize component update performance.
Created lifecycle function that triggers a component
If it is not a page root component, you need to set the property value of the component according to the property definition on the component node
When the component instance is displayed on the page, the attached lifecycle function of the component is triggered, and if there are other components in the Shadow Tree, their lifecycle functions are triggered one by one.
Component communication
Because of the responsibility of the business, we often need to split a large page into multiple components, and multiple components need to communicate with each other.
Global state management can be considered for intergenerational component communication. Only common parent-child component communication is discussed here:
Method one: WXML data binding
Used for the parent component to set data to the specified property of the child component.
Subdeclaration properties attribute
Component ({properties: {vtabs: {type: Array, value: []}, / / data item format is `{title}`}})
The parent component calls:
. the-child
Descendant selector: .the-ancestor. The-descendant
Descendant selector across custom components: .the-ancestor > .the-descendant
Union of multiple selectors: # a-node, .some-other-nodes
Method 4 url parameter communication
In WeChat Mini Programs, such as e-commerce / logistics, there are user stories such as "placing order page A" and "goods information page B".
Fill in the basic information on the "order placing page A" and drill down to the "details page B" to fill in the details. For example, a courier order page, you need to drill down to the goods information page to fill in more detailed information, and then return to the previous page.
If you drill to "goods page B" under "order page A", you need to echo the data of "goods page B".
WeChat Mini Programs consists of an App () instance and multiple Page (). The Mini Program framework maintains the page by stack (up to 10) provides the following API for page jump, and the page route is as follows
Wx.navigateTo (you can only jump to pages in the stack)
Wx.redirectTo (can jump to a new page off the stack and replace the current page)
Wx.navigateBack (returns to the previous page and cannot carry parameters)
Wx.switchTab (switch Tab page, url parameter is not supported)
Wx.reLaunch (Mini Program restart)
You can simply encapsulate a jumpTo jump function and pass parameters:
Export function jumpTo (url, options) {const baseUrl = url.split ('?) [0]; / / if url has parameters, you need to mount the parameters to options (url.indexof ('?)! =-1) {const {queries} = resolveUrl (url); Object.assign (options, queries, options) / / options has the highest priority} cosnt queryString = objectEntries (options) .filter (item = > item [1] | | item [0] = 0) / / except for the number 0 Other non-values are filtered .map (([key, value]) = > {if (typeof value = 'object') {/ / object to string value = JSON.stringify (value)) } if (typeof value = = 'string') {/ / string encode value = encodeURIComponent (value);} return `$ {key} = ${value} `;}) .join (' &') If (queryString) {/ / requires assembly parameters url = `${baseUrl}? ${queryString}`;} const pageCount = wx.getCurrentPages () .length; if (jumpType = 'navigateTo' & & pageCount
< 5) { wx.navigateTo({ url, fail: () =>{wx.switch ({url: baseUrl});}} else {wx.navigateTo ({url, fail: () = > {wx.switch ({url: baseUrl});});}}
JumpTo helper function:
Export const resolveSearch = search = > {const queries = {}; cosnt paramList = search.split ('&'); paramList.forEach (param = > {const [key, value ='] = param.split ('='); queries [key] = value;}); return queries;} Export const resolveUrl = (url) = > {if (url.indexOf ('?') = =-1) {/ / url return {queries: {}, page: url}} const [page, search] = url.split ('?'); const queries = resolveSearch (search); return {page, queries};}
Pass the data on the place order page A:
JumpTo ({url: 'pages/consignment/index', {sender: {name:' naluduo233'})
Get the URL parameters on "cargo Information Page B":
Const sender = JSON.parse (getParam ('sender') | |' {}')
Url parameter acquisition auxiliary function
/ / return the current page export function getCurrentPage () {const pageStack = wx.getCurrentPages (); const lastIndex = pageStack.length-1; const currentPage = pageStack [lastIndex]; return currentPage;} / / get the page url parameter export function getParams () {const currentPage = getCurrentPage () | | {}; const allParams = {}; const {route, options} = currentPage; if (options) {const entries = objectEntries (options) Entries.forEach (([key, value])) = > {allParams [key] = decodeURIComponent (value);} return allParams;} / / return value export function getParam (name) {const params = getParams () by field | {}; return params [name];}
What if the parameter is too long? Routing api does not support carrying parameters?
Although WeChat Mini Programs's official document does not specify how long the parameters can be carried on the page, there is still a risk that the parameters may be truncated if they are too long.
We can use global data to record parameter values and solve the problem that url parameters are too long and routing api does not support carrying parameters.
/ / global-data.js// since switchTab does not support carrying parameters, you need to consider using global data storage / / whether it is switchTab or not, mount the data to const queryMap = {page:'', queries: {}} first.
Update jump function
Export function jumpTo (url, options) {/ /. Object.assign (queryMap, {page: baseUrl, queries: options}); / / If (jumpType = = 'switchTab') {wx.switchTab ({url: baseUrl});} else if (jumpType = =' navigateTo' & & pageCount
< 5) { wx.navigateTo({ url, fail: () =>{wx.switch ({url: baseUrl});}} else {wx.navigateTo ({url, fail: () = > {wx.switch ({url: baseUrl});});}}
Url parameter acquisition auxiliary function
/ / get the page url parameter export function getParams () {const currentPage = getCurrentPage () | | {}; const allParams = {}; const {route, options} = currentPage; if (options) {const entries = objectEntries (options); entries.forEach (([key, value])) = > {allParams [key] = decodeURIComponent (value);}) + if (isTabBar (route)) {+ / / is a tab-bar page, using the parameters mounted to the global + const {page, queries} = queryMap; + if (page = `$ {route} `) {+ Object.assign (allParams, queries); +}} return allParams;}
Auxiliary function
/ / determine whether the current path is tabBarconst {tabBar} = appConfig;export isTabBar = (route) = > tabBar.list.some (({pagePath})) = > pagePath = route)
According to this logic, there is no need to distinguish whether it is an isTabBar page or not, all pages are obtained from queryMap? This question will not be concluded until later, because I have not yet tried to get a missing value from the options of the page instance. So you can keep the value of reading getCurrentPages first.
Method 5 EventChannel event dispatch communication
I mentioned earlier that data can be passed from "current page A" to "page B" that is opened through the url parameter. So what do you do if you want to get the data that the open page sends to the current page? Is it also possible to pass the url parameter?
The answer is yes, as long as you don't need to save the state of Page A. If you want to keep the state of "page A", you need to use navigateBack to return to the previous page, and this api does not support carrying the url parameter.
In this way, you can use the inter-page event communication channel EventChannel.
PageA page
/ / wx.navigateTo ({url: 'pageB?id=1', events: {/ / add a listener for the specified event Get the data acceptDataFromOpenedPage: function (data) {console.log (data)},}, success: function (res) {/ / transfer data res.eventChannel.emit ('acceptDataFromOpenerPage', {data:' test'})} to the open page via eventChannel)
PageB page
Page ({onLoad: function (option) {const eventChannel = this.getOpenerEventChannel () eventChannel.emit ('acceptDataFromOpenedPage', {data:' test'}); / / listens to the acceptDataFromOpenerPage event to get the data eventChannel.on that the previous page sent to the current page via eventChannel ('acceptDataFromOpenerPage', function (data) {console.log (data)})})
Will there be a situation in which the data cannot be monitored?
Mini Program stack is no more than 10 layers, if the current "page A" is not the 10th layer, then you can use navigateTo jump to retain the current page, jump to "page B", at this time, "page B" completed and passed the data to "page A", "page A" can listen to the data.
If the current "page A" is already the 10th page, you can only use redirectTo to jump to the "PageB" page. The result is that the current "page A" is out of the stack, and the new "page B" is on the stack. At this time, the "page B" is passed to the "page A", and the call to navigateBack cannot return to the target "page A", so the data cannot be monitored normally.
However, in the Mini Program that I have analyzed and done, there are rarely 10 layers in the stack, and there are few 5 layers in the stack. Because calling wx.navigateBack and wx.redirectTo closes the current page, calling wx.switchTab closes all other non-tabBar pages.
So it is rare that you can't go back to the previous page to listen to the data. if this happens, the first thing to consider is not the monitoring of the data, but to ensure that you can return to the previous page.
For example, in the "PageA" page, first call getCurrentPages to get the number of pages, and then delete other pages, and then jump to the "PageB" page, so as to avoid "PageA" calling wx.redirectTo to close "PageA". However, it is not recommended for developers to change the page stack manually, so you need to be careful.
If any readers encounter this situation and know how to solve it, please let me know, thank you.
Use a custom event center EventBus
In addition to using the official EventChannel, we can also customize a global EventBus event center. Because this is more flexible, there is no need to pass parameters in calling APi such as wx.navigateTo, and multi-platform mobility is stronger.
Export default class EventBus {private defineEvent = {}; / register event public register (event: string, cb): void {if (! this.defineEvent [event]) {(this.defineEvent [event] = [cb]);} else {this.defineevent [event] .push (cb) }} / / dispatch event public dispatch (event: string, arg?: any): void {if (this.defineEvent.event]) {{for (let item0, len = this.defineEvent.length; I {cb & & cb (event); this.off (event, onceCb);} this.register (event, onceCb) } / / clear all events public clean (): void {this.defineEvent = {};}} export connst eventBus = new EventBus ()
Listen on the PageA page:
EventBus.on ('update', (data) = > console.log (data))
Dispatch on the PageB page
EventBus.dispatch ('someEvent', {name:' naluduo233'}); this is the end of the article on "how to customize components in WeChat Mini Programs". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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.