当前位置:网站首页>Introduction to applet Basics (dark horse learning notes)
Introduction to applet Basics (dark horse learning notes)
2022-06-13 04:27:00 【Java becomes God】
One 、 Host environment -- Components
1.scroll-view( Rolling effect )
- scroll-y attribute : Allow vertical scrolling
- scroll-x attribute : Allow horizontal scrolling
- Be careful : When using vertical scrolling , Must give scroll-view A fixed height
2.swiper and swiper-item Basic use of components ( To achieve the effect of the rotation map )
3. text
- Text component
- Be similar to HTML Medium span label , It's an in-line element
- adopt text Component's selectable attribute , Long press the selected text content
4.rich-text
- Rich text component
- Support HTML The string is rendered as WXML structure
- adopt rich-text Component's nodes Attribute node , hold HTML The string is rendered as the corresponding UI structure :
5. button
- Button components
- Functional ratio HTML Medium button Rich buttons
- adopt open-type Attribute can call various functions provided by wechat ( Customer service 、 forward 、 Get user authorization 、 Access to user information, etc )
6. image
- Picture components
- image The default width of the component is about 300px、 The height is about 240px
7. navigator
- Page navigation component
- Be similar to HTML Medium a link
Two 、 Applet API Three categories
In the applet API Is provided by the host environment , Through these rich applets API, Developers can easily call the capabilities provided by wechat , for example : Get user information 、 The local store 、 Payment function, etc .
3、 ... and 、WXML Template syntax
1. Template syntax
- stay data Data defined in
- stay WXML Using data in
① On the page corresponding to .js In file , Define data to data In the object :
② hold data The data in is bound to render in the page , Use Mustache grammar ( Double brace ) Just wrap the variables
③Mustache Application scenario of Syntax
- Binding content
- Binding properties
- operation ( The ternary operation 、 Arithmetic operations, etc )
④ Dynamically bind content
The data of the page is as follows :
The structure of the page is as follows :
⑤ The ternary operation
The structure of the page is as follows :
⑥ Arithmetic operation
The data of the page is as follows :
The structure of the page is as follows :
2. Event binding
① What is an event
Events are the means of communication from the rendering layer to the logical layer . Through events, the user's behavior in the render layer can be , Feed back to the logic layer for business processing .
② Events commonly used in applets
③ Property list of the event object
④target and currentTarget The difference between
⑤bindtap The grammar of
⑥ In the event handler function is data Data assignment in
By calling this.setData(dataObject) Method , You can give pages data Reassign the data in , Examples are as follows :
⑦ Event biography
The event parameters in the applet are special , You cannot pass parameters to an event handler while binding an event . for example , The following code will not be positive Work often :
Because the applet will bindtap The attribute value , It is treated as an event name , Equivalent to calling a btnHandler(123) Event handler for .
Can provide... For components data-* Custom attribute transfer parameter , among * Represents the name of the parameter , The sample code is as follows :
Final :
- info Will be resolved to the name of the parameter
- The number 2 Will be resolved to the value of the parameter
In the event handler , adopt event.target.dataset. Parameter name You can get the value of specific parameters , The sample code is as follows
⑧bindinput The grammar of
In the applet , adopt input Event in response to the input event of the text box , The syntax is as follows :
① adopt bindinput, You can enter events for text box binding :
② On page .js Event handling functions defined in the file :
⑨ Implement text boxes and data Data synchronization between
Implementation steps :
- Defining data
- Render structure
- Beautification style
- binding input Event handler
Defining data :
Render structure :
Beautification style :
binding input Event handler :
3、 Conditions apply colours to a drawing
①wx:if
In the applet , Use wx:if="{ {condition}}" To determine whether the code block needs to be rendered :
It can also be used. wx:elif and wx:else To add else Judge :
② combination Use wx:if
If you want to control the display and hiding of multiple components at one time , You can use one Tags wrap multiple components , And in Use on label wx:if Control properties , Examples are as follows :
Be careful : It's not a component , It's just a package container , No rendering in the page .
③ hidden
In the applet , Use it directly hidden="{ { condition }}" It can also control the display and hiding of elements :
④ .wx:if And hidden Comparison of
① The operation mode is different
- wx:if By dynamically creating and removing elements , Control the display and hiding of elements
- hidden By switching styles (display: none/block;), Control the display and hiding of elements
② Use advice
- When switching frequently , It is recommended to use hidden
- When the control conditions are complex , It is recommended to use wx:if collocation wx:elif、wx:else Switch between show and hide
4、 The list of rendering
①wx:for
adopt wx:for According to the specified array , Loop render duplicate component structures , Examples of syntax are as follows :
By default , The index reference of the current circular item index Express ; Current circular item item Express
② Manually specify the index and the variable name of the current item *
- Use wx:for-index You can specify the variable name of the index of the current circular item
- Use wx:for-item You can specify the variable name of the current item
③wx:key Use
Be similar to Vue List rendering :key, When the applet realizes list rendering , It is also recommended that you specify a unique name for the rendered list item key value , So as to improve the efficiency of rendering , The sample code is as follows :
Four 、WXSS Template style
1.rpx Unit of measure
rpx(responsive pixel) It is unique to wechat applet , Size unit used to solve screen adaptation .
① Realization principle
rpx The implementation principle of is very simple : Given the different screen sizes of different devices , In order to realize the automatic adaptation of the screen ,rpx Put all the devices on the screen , Divide equally in width 750 Share ( namely : The total width of the current screen is 750rpx).
- On smaller devices ,1rpx The width represented is small
- On larger devices ,1rpx The width represented is large
When applets run on different devices , Will automatically rpx The style units are converted to the corresponding pixel units to render , So as to realize screen adaptation .
2. Style import
Use WXSS Provided @import grammar , You can import an external style sheet .
@import Followed by the relative path of the external stylesheet to be imported , use ; End of statement . Examples are as follows :
5、 ... and 、 Global configuration and page configuration
Be careful :
- When a local style conflicts with a global style , According to the principle of proximity , Local styles override global styles
- When the weight of the local style is greater than or equal to the weight of the global style , Will override the global style
1. Global configuration files and common configuration items
In the applet root directory app.json File is the global configuration file of the applet . Common configuration items are as follows :
① pages
Record the storage path of all pages of the current applet
② window
Set the appearance of the applet window globally
③ tabBar
Set the at the bottom of the applet tabBar effect
④ style
Whether to enable the new component style
2. Global configuration -window Common configuration items of nodes
3. Global configuration -tabBar
tabBar It is a common page effect in mobile applications , Used to implement multiple pages Fast switching . Small programs are usually divided into :
- Bottom tabBar
- Top tabBar
Be careful :
- tabBar You can only configure least 2 individual 、 most 5 individual tab Tab
- When rendering Top tabBar when , No display icon, Show only text
①tabBar Of 6 Components
②tabBar Configuration item of node
③ Every tab Configuration options for item
4. Page profile
① effect
Small program , Each page has its own .json The configuration file , Used to the window appearance of the current page 、 Page effect, etc .
② The relationship between page configuration and global configuration
Small program ,app.json Medium window node , You can globally configure the window performance of each page in the applet .
If some applet pages want to have special window performance , here ,“ Page level .json The configuration file ” You can achieve this demand .
Be careful : When the page configuration conflicts with the global configuration , According to the principle of proximity , The final effect is subject to the page configuration .
③ Common configuration items in page configuration
7、 ... and 、 Network data request
1. Restrictions on network data requests in applets
For security reasons , The official request of the applet for the data interface is as follows There are two restrictions :
- Only request HTTPS Interface of type
- The domain name of the interface must be added to the trust list
2. To configure request Legitimate domain name
Requirements describe : Suppose in your own wechat applet , Hope request https://www.escook.cn/ Interface under domain name
Configuration steps : Log in to wechat applet management background -> Development -> Development and setup -> Server domain name -> modify request Legitimate domain name
matters needing attention :
- Domain name only supports https agreement
- Domain name cannot be used IP Address or localhost
- The domain name must go through ICP Keep on record
- The server domain name can be applied for at most within one month 5 Time modification
3. launch GET request
Call the information provided by wechat applet wx.request() Method , Can initiate GET Data request , The sample code is as follows :
getSwiperList(){
wx.request({
url: 'https://applet-base-api-t.itheima.net/slides',
method:'GET',
success:(res)=>{
console.log(res);
this.setData({
setWifiList:res.data
})
}
})
},
4. launch POST request
Call the information provided by wechat applet wx.request() Method , Can initiate POST Data request , The sample code is as follows :
5. Request data when the page is just loaded
In many cases , We need to load the page at the beginning , Automatically request some initialization data . At this time, you need to enter the... On the page onLoad event Function to call data in , The sample code is as follows :
6. skip request Legal domain name verification
If the back-end programmer Only... Is provided http Interface to protocol 、 Not available for the time being https Interface to protocol .
At this time, in order not to delay the progress of development , We can use wechat developer tools , temporary Turn on 「 The development environment does not verify the requested domain name 、TLS Version and HTTPS certificate 」 Options , skip request Verification of legal domain name .
Be careful : skip request Options for legal domain name verification , Use only during the development and commissioning phase !
7. About cross domain and Ajax Explanation
Cross domain problems only exist in browser based systems Web In development . because The host environment of the applet Not a browser , It is Wechat client , therefore There is no cross domain problem in applets .
Ajax The core of the technology is to rely on... In the browser XMLHttpRequest This object , because The hosting environment of the applet is wechat client , So the applet cannot be called “ launch Ajax request ”, It is called “ Initiate a network data request ”.
8、 ... and 、 Page navigation
1. There are two ways to realize page navigation in applet
- Declarative navigation
- Declare a... On the page Navigation components
- By clicking on Component to realize page Jump
- Programming navigation
- Calling applet navigation API, Realize page Jump
2. Declarative navigation
① Navigate to tabBar page
tabBar A page refers to a page that is configured to tabBar The page of .
In the use of The component jumps to the specified tabBar When the page is , You need to specify the url Properties and open-type attribute , among :
- url Indicates the address of the page to jump to , Must be / start
- open-type Indicates how to jump , It has to be for switchTab
The sample code is as follows :
② Navigate to non tabBar page
Not tabBar A page is one that is not configured to tabBar The page of .
In the use of The component jumps to the normal non tabBar When the page is , You need to specify url Properties and open-type attribute , among :
- url Indicates the address of the page to jump to , Must be / start
- open-type Indicates how to jump , It has to be for navigate
The sample code is as follows :
③ Back navigation
If you want to go back to the previous page or multi-level page , You need to specify open-type Properties and delta attribute , among :
- open-type The value of must be navigateBack, Indicates that you want to perform back navigation
- delta The value of must be a number , Indicates the level to go back
The sample code is as follows :
Be careful : For simplicity , If you just go back to the previous page , You can omit delta attribute , Because the default value is 1
3. Programming navigation
① Navigate to tabBar page
call wx.switchTab(Object object) Method , You can jump to tabBar page . among Object The attribute list of the parameter object is as follows :
The sample code is as follows :
② Navigate to non tabBar page
call wx.navigateTo(Object object) Method , You can jump to non tabBar The page of . among Object Attribute list of parameter object as follows :
The sample code is as follows :
③. Back navigation
call wx.navigateBack(Object object) Method , You can return to the previous page or multiple pages . among Object The parameter object is optional The list of attributes is as follows :
The sample code is as follows :
Nine 、 Navigation parameters
1. Declarative navigation parameters
navigator Component's url Property is used to specify the path of the page to jump to . meanwhile , Parameters can also be carried behind the path :
- Use... Between parameters and paths ? Separate
- Parameter key and parameter value = Connected to a
- Use... For different parameters & Separate
The code example is as follows :
2. Programming navigation parameters
call wx.navigateTo(Object object) Method to jump to the page , You can also carry parameters ,
The code example is as follows :
3. stay onLoad Receive navigation parameters in
Parameters carried by declarative navigation parameters or programmatic navigation parameters , Can be directly in onLoad Get directly from the event
The sample code is as follows :
Ten 、 Applet page Events
1. Drop down refresh event
① What is pull-down refresh
Pull down refresh is a proper term for mobile terminal , It refers to the pull-down and sliding operation of your finger on the screen , To reload page data .
② Enable pull-down refresh
There are two ways to enable pull-down refresh :
- Global enable pull-down refresh
- stay app.json Of window In nodes , take enablePullDownRefresh Set to true
- Local open pull-down refresh
- On page .json In profile , take enablePullDownRefresh Set to true
In actual development , Recommended use of 2 Ways of planting , Open the drop-down refresh effect separately for the required page .
③ Configure the style of the drop-down refresh window
At the global or page level .json In profile , adopt backgroundColor and backgroundTextStyle To configure the drop-down refresh window The style of , among :
- backgroundColor Used to configure the background color of the drop-down refresh window , Support only 16 The color value of base
- backgroundTextStyle Used to configure pull-down refresh loading The style of , Support only dark and light
④ Listen for the drop-down refresh event of the page
On page .js In file , adopt onPullDownRefresh() Function to listen to the pull-down refresh event of the current page .
When the pull-down refresh event of the page is triggered , If you want to put the count The value of is reset to 0, The sample code is as follows :
⑤ Stop the effect of pull-down refresh
After processing the pull-down refresh , Drop down to refresh loading The effect will always show , Will not take the initiative to disappear , So you need to manually hide the drop-down refresh loading effect . here , call wx.stopPullDownRefresh() You can stop the pull-down refresh of the current page . The sample code is as follows :
2. Pull up bottoming Events
① What is pulling up to the bottom
Pull up to touch the bottom is a proper term for mobile terminal , Pull up and slide the screen with your fingers , So as to load more data .
② Listen for the bottom pulling event of the page
On page .js In file , adopt onReachBottom() Function to listen to the pull-up bottom event of the current page . The sample code is as follows :
③ Configure the pull-up bottom touch distance
The pull-up bottom touch distance refers to when the pull-up bottom touch event is triggered , The distance from the scroll bar to the bottom of the page .
It can be displayed globally or on the page .json In profile , adopt onReachBottomDistance Property to configure the distance of pulling up to the bottom .
The default bottom touch distance of the applet is 50px, In actual development , You can modify this default value according to your needs .
3. Throttle the pull-up contact bottom
- stay data in Definition isloading throttle valve
- false Indicates that no data request is currently in progress
- true Indicates that a data request is currently in progress
- stay getColors() In the method modify isloading The value of the throttle valve
- Just called getColors Set the throttle valve to true
- Request on the network complete In the callback function , Reset the throttle valve to false
- stay onReachBottom in Judge The value of the throttle valve , So as to throttle the data request
- If the value of the throttle valve is true, Block the current request
- If the value of the throttle valve is false, Then initiate a data request
11、 ... and 、 Applet life cycle
1. What is life cycle
Life cycle (Life Cycle) Refers to an object from establish -> function -> The destruction The whole stage of , The emphasis is on a time period . for example :
- Zhang San was born , Indicates the beginning of the person's life cycle
- Zhang San died , Indicates the end of the person's life cycle
- Zhang San's life in the middle , Is Zhang San's life cycle
We can put the process of running each applet , It can also be summarized as the life cycle :
- Start of applet , Indicates the beginning of the life cycle
- Close the applet , Indicates the end of the life cycle
- The process of running an intermediate applet , Is the life cycle of the applet
2. Classification of life cycle
In the applet , The life cycle is divided into two categories , Namely :
- Application life cycle
- Especially when an applet starts from -> function -> The process of destruction
- Page lifecycle
- Especially in small programs , Loading of each page -> Rendering -> The process of destruction
among , The life cycle of the page is small , The life cycle of an application has a wide range , As shown in the figure :
3. What is a life cycle function
Life cycle function : Is a built-in function provided by the applet framework , With the life cycle , Automatically execute in order .
The function of life cycle function : Allow programmers to at a specific point in time , Perform certain operations . for example , When the page was just loaded , Can be in onLoad Initialize the data of the page in the life cycle function .
Be careful : Life cycle emphasizes time period , The life cycle function emphasizes the point in time .
4. Classification of life cycle functions
Life cycle functions in applets fall into two categories , Namely :
① Applied life cycle function
Especially when an applet starts from -> function -> Those functions called in turn during destruction
② Life cycle function of page
Especially in small programs , Each page is loaded from -> Rendering -> Those functions called in turn during destruction
5. Applied life cycle function
The application life cycle function of the applet needs to be in app.js To declare , The sample code is as follows :
6. Life cycle function of page
The page life cycle function of the applet needs to be in the page .js Make a statement in the document , The sample code is as follows :
Twelve 、WXS Script
1. What is? wxs
WXS(WeiXin Script) It is a set of script language unique to small programs , combination WXML, You can build the structure of the page .
2.wxs Application scenarios of
wxml Cannot call in the page .js The function defined in , however ,wxml Can be called wxs The function defined in . therefore , Small program wxs Of Typical application scenarios Namely “ filter ”.
3.wxs and JavaScript The relationship between *
although wxs The grammar of is similar to JavaScript, however wxs and JavaScript Are two completely different languages :
① wxs It has its own data type
number value type 、string String type 、boolean Boolean type 、object object type
function Function type 、array An array type 、 date The date type 、 regexp Regular
② wxs No support similar to ES6 And the above grammatical forms
I won't support it :let、const、 Deconstruct assignment 、 Expand operator 、 Arrow function 、 Object attribute shorthand 、etc...
Support :var Defining variables 、 Ordinary function Functions, etc. are similar to ES5 The grammar of
③ wxs follow CommonJS standard
module object
require() function
module.exports object
4. Embedded wxs Script
wxs The code can be written in wxml In the document <wxs> tag , It's like Javascript The code can be written in html Of documents <script> It's the same inside the label .
wxml Every... In the document <wxs></wxs> label , You must provide module attribute , Used to specify At present wxs Module name , Convenient in wxml Access the members in the module :
5. Define the of outreach wxs Script
wxs The code can also be written in .wxs The suffix for the file inside , It's like javascript The code can be written in .js For the suffix in the file equally . The sample code is as follows :
6. Using extranet wxs Script
stay wxml Introduce outreach in wxs Script time , It has to be for add module and src attribute , among :
- module Used to specify the name of the module
- src Used to specify the path of the script to be imported , And it has to be a relative path
The sample code is as follows :
7.WXS Characteristics
1. Cannot be used as an event callback for a component
wxs A typical application scenario is “ filter ”, Often cooperate with Mustache Using grammar , for example :
however , stay wxs The function defined in Cannot be used as an event callback function of a component . for example , The following usage is wrong :
2. Isolation,
Isolation means wxs Operating environment and other JavaScript The code is isolated . Reflected in the following two aspects :
- wxs Cannot call js The function defined in
- wxs Cannot call the API
3. Good performance
- stay iOS On the device , In the applet WXS than JavaScript The code is fast 2 ~ 20 times
- stay android On the device , There is no difference in operation efficiency between the two
8. List page Main function realization
① Use of throttle valve
- First, define a throttle variable in the data area ( The initial value is false, Means no data is being obtained )
- In the get data function First Set the throttle variable to true( Indicates that data is being obtained )
- Last , After the request is completed , The throttle variable must be set to... Regardless of success false.
② Pull up bottoming Events
- All the code for this event needs to be in onReachBottom() Write in .
- First judge whether there is data on the next page
- Judge the condition : Page number value * How many pieces of data are displayed per page >= Total number of data (page * pageSize >= total)
- Determine whether other data is being loaded
- Set the page number value plus one ( The parameter that initiates the request for data on the next page )
- Finally, call the function to get the data
③ Drop down refresh event
- First in json In the domain enablePullDownRefresh Set to true
And then in onPullDownRefresh Write logic code in function
Set key data ( Page number , Data list , Total data )
Re launch the request
Finally, remember to call wx.stopPullDownRefresh(); Turn off pull-down refresh
13、 ... and 、 Create and reference custom components
1. Create components
- In the root directory of the project , Right mouse button , establish components -> test Folder
- In the new components -> test folder , Right mouse button , Click on “ newly build Component”
- Type the name of the component and press enter , The corresponding... Of the component will be generated automatically 4 File , The suffixes are .js,.json, .wxml and .wxss
Be careful : In order to ensure the clarity of the directory structure , It is recommended that different components , Store in a separate directory , for example :
2. Refer to the component
The reference methods of components are divided into “ Partial quote ” and “ Global references ”, seeing the name of a thing one thinks of its function :
- Partial quote : Components can only be used within the currently referenced page
- On page .json How components are referenced in the configuration file , be called “ Partial quote ”. The sample code is as follows :
- On page .json How components are referenced in the configuration file , be called “ Partial quote ”. The sample code is as follows :
3. The difference between a global reference and a local reference
According to the frequency and range of components , To choose the appropriate reference method :( On-demand reference )
- If a component is often used in multiple pages , Recommended “ Global references ”
- If a component is only used in a specific page , Recommended “ Partial quote “
4. Differences between components and pages
On the surface , Components and pages are made up of .js、.json、.wxml and .wxss These four documents make up . however , Components and pages .js And .json The files are obviously different :
- Component's .json Declaration required in document "component": true attribute
- Component's .js What is called in the file is Component() function
- Component's Event handler Need to define to methods node in
fourteen 、 Custom component styles
1. Component style isolation
By default , The style of a custom component is only valid for the current component , Will not affect... Outside the component UI structure , As shown in the figure :
- Components A The style of does not affect the component C The style of
- Components A The style of does not affect the style of the applet page
- The style of the applet page does not affect the component A and C The style of
benefits :
- Prevent external styles from affecting internal styles of components
- Prevent component styles from damaging external styles
2. Notes on component style isolation
- app.wxss The global style in is not valid for the component
- Only class The selector will have the effect of style isolation ,id Selectors 、 Attribute selector 、 tag chooser Not affected by style isolation
Suggest : It is recommended to use... In components and pages referencing components class Selectors , Do not use id、 attribute 、 tag chooser !
3. Modify style isolation options for components
By default , For custom components Style isolation properties can Prevent the internal and external styles of components from interfering with each other . But sometimes , We hope to be able to Control the style inside the component , here , Can pass styleIsolation Modify style isolation options for components , Usage is as follows :
styleIsolation Optional values for :
15、 ... and 、 Custom components - data 、 Methods and properties
1.data data
In applet components , For component template rendering Private data , Need to define to data In nodes .
2.properties attribute
In applet components ,properties It's a component External attribute , be used for Receive the data transferred from the outside to the component . The sample code is as follows :
3.data and properties The difference between
In the components of the applet ,properties Properties and data The usage of data is the same , They are all Can read but write Of , It's just :
- data More inclined to store components private data
- properties More inclined to Store external transmission To the data in the component
4.methods Method
In applet components , Event handlers and custom methods Need to define to methods In nodes .
sixteen 、 Custom components - Data listener
1. What is a data listener
Data listeners are used to listen and respond Any changes in attributes and data fields , To perform specific operations . Its function is similar to vue Medium watch The listener . In applet components , The basic syntax format of the data listener is as follows :
2. Basic usage of data listener
① Component's UI The structure is as follows :
② Component's .js The document code is as follows :
3. Listen for changes in object properties
The data listener supports monitoring the changes of single or multiple attributes in the object , The example syntax is as follows :
4. Listen for changes to all properties in the object
If there are too many attributes in an object that need to be monitored , For convenience , have access to wildcard ** To listen to objects All attributes The change of , The sample code is as follows :
seventeen 、 Custom components - Pure data fields
1. What is a pure data field
Concept : Pure data fields are those that Not used for interface rendering Of data Field .
Application scenarios : For example, in some cases , some data The fields in will not be displayed on the interface , It will not be passed to other components , Use only within the current component . With this characteristic data The field is suitable to be set as a pure data field .
benefits : Pure data fields help improve the performance of page updates .
2. Usage rule
stay Component Constructor's options In nodes , Appoint pureDataPattern For a regular expression , The field name matches this rule The field of the expression will become a pure data field , The sample code is as follows :
eighteen 、 Custom components - Life cycle of components
1. The entire lifecycle function of the component
The full life cycle available for applet components is shown in the following table :
2. The main life cycle functions of components
In applet components , The most important life cycle functions are 3 individual , Namely created、attached、detached. Their respective characteristics as follows :
- Component instance Just created When ,created The lifecycle function will be triggered
- Also at this time Cannot call setData
- Usually in this life cycle function , Should only be used for components this Add some custom attribute fields
- In components Complete initialization 、 After entering the page node tree , attached The lifecycle function will be triggered
- here , this.data Has been initialized
- This life cycle is very useful , Most initialization can be done at this time ( For example, send a request to get the initial data )
- In components After leaving the page node tree , detached The lifecycle function will be triggered
- When exiting a page , It will trigger the of each custom component in the page detached Life cycle function
- At this time, it is suitable to do some cleaning work
3.lifetimes node
In applet components , Life cycle functions can be defined directly in Component In the first level parameters of the constructor , Sure stay lifetimes Field Inside Statement ( This is the recommended way , It has the highest priority ). The sample code is as follows :
nineteen 、 Custom components - The life cycle of the page on which the component resides
1. What is the life cycle of the page where the component is located
Sometimes , The behavior of custom components depends on the change of page state , At this point, you need to use the life cycle of the page where the component is located . In custom components , The life cycle functions of the page where the component is located are as follows 3 individual , Namely :
2.pageLifetimes node
The lifecycle function of the page where the component is located , Need to be defined in pageLifetimes node in , The sample code is as follows :
twenty 、 Custom components - slot
1. What is a slot
In the custom component of wxml In structure , Can provide a node <slot>( slot ), Used to host the... Provided by the component consumer wxml structure .
2. Enable multiple slots
In the custom component of the applet , By default, only one slot can be used , When multiple slots are required , It can be found in the component's .js In file , Enable by . The sample code is as follows :
3. Define multiple slots
It can be found in the component's .wxml Using multiple in label , In different ways name To distinguish between different slots . The sample code is as follows :
When using custom components with multiple slots , Need to use slot Property to insert nodes into different in . The sample code is as follows :
The 21st 、 Custom components - Communication between parent and child components
1. Communication between parent and child components 3 Ways of planting
- ① Attribute binding
- be used for Parent component to child component Set data for the specified attribute of , You can only set JSON Compatible data
- ② Event binding
- be used for Child component to parent component To transfer data , You can pass any data
- ③ Get component instance
- Parent component You can also use this.selectComponent() Get sub component instance object
- In this way, you can directly access any data and methods of sub components
2. Attribute binding
Property binding is used for Realize the transfer of values from parent to child , and Only ordinary types of data can be passed , Cannot pass method to child component . The sample code of the parent component is as follows :
Child components stay properties node Declare the corresponding properties in and use . The sample code is as follows :
3. Event binding
Event binding is used to implement Pass from son to father , Can pass any type of data . Use step as follows :
- stay Parent component Of js in , Define a function , This function will be in the form of custom events , Pass to subcomponent
- stay Parent component Of wxml in , In the form of custom events , Will step 1 Function reference defined in , Pass to subcomponent
- In subcomponent js in , adopt call this.triggerEvent(' Custom event name ', { /* Parameter object */ }) , Send data to parent component
- stay Parent component Of js in , adopt e.detail Get the data passed from the sub component
① step 1: In the parent component of js in , Define a function , This function will be in the form of custom events , Pass to subcomponent .
② step 2: In the parent component of wxml in , In the form of custom events , Will step 1 Function reference defined in , Pass to subcomponent .
③ step 3: In subcomponent js in , By calling this.triggerEvent(‘ Custom event name ’, { /* Parameter object */ }) , Send data to parent component .
④ step 4: In the parent component of js in , adopt e.detail Get the data passed from the sub component .
4. Get component instance
Can be called in the parent component this.selectComponent("id or class Selectors ") , Get the instance object of the subcomponent , So as to directly access any data and methods of sub components . You need to pass in a Selectors , for example this.selectComponent(".my-component").
Twenty-two 、 Custom components - behaviors
1. What is? behaviors
behaviors It's in the applet , be used for Realize code sharing between components Characteristics of , Be similar to Vue.js Medium “mixins”.
2. behaviors How it works
Every behavior Can contain a set of attribute 、 data 、 Life cycle functions and methods . When a component references it , Its properties 、 Data and methods will be Merge into components .
Each component can reference more than one behavior,behavior You can also quote other behavior.
3. establish behavior
call Behavior(Object object) Method to create a shared behavior Instance object , For all components :
4. Import and use behavior
In components , Use require(" route ") Method Import required behavior, Once mounted, you can access behavior Data or methods in , The sample code is as follows :
5.behavior All available nodes in
6. Overwrite and combination rules of fields with the same name *
Component and what it references behavior Fields with the same name can be included in , At this point, you can refer to the following 3 A processing rule with the same name :
① A data field with the same name (data)
② Property with the same name (properties) Or method (methods)
③ Life cycle function with the same name
Please refer to the instructions given in the official wechat applet documentation :
23 、 Use npm package
1. The app is right npm Support and limitations of
at present , Applets already support the use of npm Install third party package , So as to improve the development efficiency of small programs . however , Used in small programs npm The package is as follows 3 A limit :
① Dependency on is not supported Node.js Package with built-in Library
② Packages that depend on browser built-in objects are not supported
③ Dependency on is not supported C++ Package of plug-ins
summary : although npm There are tens of millions of bags on the , But packages that can be used by applets are “ Not many ”.
2. What is? Vant Weapp
Vant Weapp It is a set of small programs that are open-source by the front-end team UI Component library , Help developers quickly build small application . It uses MIT Open source license agreement , Friendly for commercial use .
Official document address :
3. install Vant Component library
In the applet project , install Vant Component libraries are mainly divided into the following 3 Step :
① adopt npm install ( It is recommended to specify a version of @1.3.3)
② structure npm package ( It is recommended to delete the previously built package before each build , Prevent accidents )
③ modify app.json
Detailed operation steps , You can refer to Vant Official quick start tutorial :
4. Use Vant Components
installed Vant After the component library , Can be in app.json Of usingComponents node Introduce the required components in , Can be in wxml in Use components directly . The sample code is as follows :
5. Customize the global theme style
Vant Weapp Use CSS Variable to implement a custom theme .
Declare a custom property , Property names need to be marked with two minus signs (
--
) Start , Property values can be any valid CSS value . As with other properties , Custom attributes are also written in Within the rule set Of , as follows :element { --main-bg-color: brown; }
Be careful :
- Rule set The selector specified defines the of the custom attribute Visible scope .
- The custom attribute name is Case sensitive Of ,
--my-color
and--My-color
Will be considered two different custom properties .As mentioned earlier , When you use a local variable, use var() function Wrap to represent a legal attribute value :
element { background-color: var(--main-bg-color); }
About CSS Variable More detailed basic usage , Please refer to MDN file :
stay app.wxss in , write in CSS Variable , It will take effect globally ( modify Vant Style of component ):
All available color variables , Please refer to Vant Officially provided configuration file :
Twenty-four 、API Promise turn
1. Asynchronous based on callback function API The shortcomings of
By default , The applet is officially provided asynchronous API Are based on callback function implementation Of , for example , The network requested API We need to follow the following steps Modal call :
shortcoming : Easy to cause Back to hell The problem of , Code readability 、 Poor maintenance !
2. What is? API Promise turn
API Promise turn , Means by Extra configuration , Will be officially provided by 、 Asynchronous based on callback function API, Upgrade to be based on Promise The asynchronous API, To improve the readability of the code 、 Maintenance , Avoid calling back to hell .
3. Realization API Promise turn
In the applet , Realization API Promise Urbanization mainly depends on miniprogram-api-promise This third party npm package . Its installation And the use steps are as follows :
① First step : install npm package
② In the applet entry file (app. js), Just call... Once promisifyAll() Method
③ call Promise Asynchrony after API
twenty-five 、 Global data sharing
1. What is global data sharing
Global data sharing ( Also known as : State management ) To solve the problem Data sharing between components The problem of . Common global data sharing schemes in development include :Vuex、Redux、MobX etc. .
2. Global data sharing scheme in applet
In the applet , You can use mobx-miniprogram coordination mobx-miniprogram-bindings Realize global data sharing . among :
- mobx-miniprogram be used for establish Store Instance object
- mobx-miniprogram-bindings be used for hold Store Shared data or methods in , Bind to a component or page to use
hexacosa- 、 Use MobX
1. install MobX Related to the package
Run the following command in the project , install MobX Related to the package :
Be careful :MobX After the relevant packages are installed , Remember Delete first miniprogram_npm Catalog after , Again structure npm.
2. establish MobX Of Store example
① Create a folder dedicated to store example
// Here js In file , Specifically to create Store Instance object of
import{observable,action} from 'mobx-miniprogram'
export const store= observable({
// Data field
numA:1,
numB:2,
// Compute properties ,get Indicates that only
get sum(){
return this.numA+this.numB;
},
//action function , Specially used to modify stpre The data in
updateNumA:action(function(step){
this.numA+=step;
}),
updateNumB:action(function(step){
this.numB+=step;
})
})
3. take Store The members in are bound to the page
4. Use on the page Store Members of the
5. take Store Bind members in to components
6. Use in components Store Members of the
twenty-seven 、 to subcontract
1. What is subcontracting
Subcontracting refers to putting a Complete applet project , According to the demand Divided into different sub packages , Package into different sub packages at build time , The user is using when Load on demand .
Benefits of subcontracting :
1. Sure Optimize Download time when the applet is first started
2. It can be better in the joint development of multiple teams Decoupling collaboration
2. Composition of the project after subcontracting
After subcontracting , The applet project consists of 1 Primary package + Multiple subcontracts make up :
1. Main package : Generally, it only includes the of the project Launch page or TabBar page 、 And some that are needed for all subcontracts public resource
2. to subcontract : It only contains pages and private resources related to the current subcontract
3. Subcontracting loading rules
① When the applet starts , Default meeting Download the main package and Start the page in the main package
tabBar The page needs to be placed in the main package
② When the user enters a page in the subcontract , The client will download the corresponding subcontracting , After the download is completed, it will be displayed
Not tabBar The page can be divided into different functions , After being divided into different subcontracts , Download on demand
4. Volume limit of subcontracting
at present , There are two restrictions on the size of applet subcontracting :
- The size of all packets of the whole small program shall not exceed 16M( Main package + All subcontracts )
- Single subcontract / The main packet size cannot exceed 2M
5. Subcontracting configuration method
6. Packaging principles
① The applet will press subpackages Subcontract the configuration of ,subpackages Directories other than will be packaged into the main package
② The main package can also have its own pages( The outermost layer pages Field )
③ tabBar The page must be in the main package
④ Subcontracting cannot be nested with each other
7. Subcontracting quotation principle
① Main package Can't quote Private resources within the subcontract
② Between subcontractors You can't quote each other Private resources
③ to subcontract You can reference Public resources in the main package
Twenty-eight 、 Independent subcontracting
1. What is independent subcontracting
Independent subcontracting is essentially subcontracting , But it's special , It can run independently of the main package and other subcontracts .
2. The difference between independent subcontracting and ordinary subcontracting
The main difference : Whether it depends on the main package to run
- Ordinary subcontracting must rely on the main package to run
- Independent subcontracting can be done without downloading the main package , Independent operation
3. Application scenarios of independent subcontracting
Developers can , Configure some pages with certain functional independence into independent subcontracting . Here's why :
- When the applet starts from the normal subcontracting page , You need to download the main package first
- Independent subcontracting can run without relying on the main package , It can greatly improve the startup speed of subcontracting page
Be careful : There can be multiple independent subcontractors in an applet .
4. Independent subcontracting configuration method
5. Citation principle
Between independent subcontracting and ordinary subcontracting and main subcontracting , Are isolated from each other , Cannot refer to each other's resources !
for example :
① Main package Can't quote Private resources in independent subcontracting
② Between independent subcontractors , You can't quote each other Private resources
③ Between independent subcontracting and ordinary subcontracting , You can't quote each other Private resources
④ Particular attention : Public resources in the main package cannot be referenced in independent subcontracting
Twenty-nine 、 Subcontracting pre download
1. What is subcontracting pre download
Subcontracting pre download refers to : When entering a page of the applet , The framework automatically pre downloads the subcontracts that may be required , So as to promote the subsequent subcontracting Page startup speed .
2. Configure the pre download of subcontracting
Pre download subcontracting behavior , Will trigger... When entering the specified page . stay app.json in , Use preloadRule Node defines the pre download of subcontracting The rules , The sample code is as follows :
3. Restrictions on subcontracting pre download
Pages in the same subcontract share a common pre download size limit 2M.
thirty 、 Customize tabBar
Customize tabBar It is divided into 3 Big steps , Namely :
① Configuration information
② add to tabBar Code file
③ To write tabBar Code
The detailed steps , You can refer to the official documentation of the applet :
边栏推荐
- 出现Could not find com.scwang.smart:refresh-layout-kernel:2.0.3.Required by: project :app 无法加载第三方包情况
- Click change color to change subscript
- Solve the problem of running server nodemon reporting errors
- Introduction and use of ES6
- Solution to failure to download files by wechat scanning QR code
- Redis data persistence
- 一款开源的Markdown转富文本编辑器的实现原理剖析
- Mongodb compass connects to the Alibaba cloud remote server database or reports an error occurred while loading instance info: command hostinfo req
- El expression
- php开发博客系统的首页头部功能实现
猜你喜欢
第007天:go语言字符串
How to use debounce in lodash to realize anti shake
Small program imitating Taobao Jiugong grid sliding effect
【Flutter 问题系列第 67 篇】在 Flutter 中使用 Get 插件在 Dialog 弹窗中不能二次跳转路由问题的解决方案
dumi 搭建文档型博客
记录一次排查问题的经过——视频通话无法接起
Knife4j aggregation 2.0.9 supports automatic refresh of routing documents
MCU: NEC protocol infrared remote controller
Intervention analysis + pseudo regression
Single chip microcomputer: basic concepts of a/d and d/a
随机推荐
Single chip microcomputer: pcf8591 application program
php开发博客系统的首页头部功能实现
Hugo blog building tutorial
El expression
【自动化测试】关于unittest你需要知道的事
高等数学(第七版)同济大学 习题1-3 个人解答
Single chip microcomputer: basic concepts of a/d and d/a
Koa file upload and download
【剑指Offer】面试题25.合并两个有序的链表
Ionic Cordova command line
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-3 personal solutions
Get parameters on link
重读经典:《End-to-End Object Detection with Transformers》
史上最详细的Swin-Transformer 掩码机制(mask of window attentation)————shaoshuai
[notes] summarize common horizontal and vertical centering methods
2019 Blue Bridge Cup
Analyse du principe de mise en œuvre d'un éditeur de texte open source markdown - to - rich
力扣刷题647.回文子串
Ultra quicksort reverse sequence pair
Call C function in Lua