vsc installation plug-in (applet development assistant - wechat applet development assistant)
Then you can start with wx - in vsc, and there will be a prompt
alt + up and down arrow move code
ctrl + alt + ↓: copy the current line down
Daily attention:
1. There must be no space between the string and curly braces, otherwise the recognition will fail
//The following is an example of an error <checkbox checked=" {{ischecked}}" ></checkbox>
Use of WXS module of wechat applet
- https://blog.csdn.net/k464746/article/details/107933625
frame
MINA native framework
1 applet structure and traditional web structure
structure | Traditional web | Wechat applet |
---|---|---|
structure | HTML | WXML |
style | CSS | WCSS |
logic | Javascript | Javascript |
to configure | JSON |
Through the above comparison, wechat applet has one more layer of configuration json
2 basic project directory
-
pages page file
index home page
logs log page
-
utils third party js Library
-
app. Global entry file of JS project
-
app.json global configuration file
-
app.wxss global style configuration
-
project. config. Configuration file of JSON project, such as appid
-
sitemap.json wechat index configuration file
3. Configure app globally js
Note: configure app JS is best equipped in the wechat development tool, and there will be a prompt
app.js global configuration includes all page paths, interface performance, network timeout, bottom tab, etc. of the applet
- The pages field is used to describe all the page paths of the current applet and let the wechat client know which directory the applet's page is defined in
- The window field defines all the top background colors and text color definitions of the applet
//app.json { "pages":{ }, "window":{ } }
4. Operation = > expression
-
You can add the expression - "statement" in curly braces
-
expression
It refers to some simple operations, numerical operations, string splicing, logical operations...
- Addition and subtraction of numbers
- String splicing
- Ternary expression
-
sentence
- Copied code snippet
- if else
- switch
- do while ...
- for ...
- Copied code snippet
-
{{1+2}} //3
5. List cycle
- wx:for = "{{array or object}}" wx:for item = "name of circular item" wx:for index = "index of circular item"
- wx:key = "unique value" is used to improve the performance of list rendering
- When wx:key binds an ordinary string, the name of the string must be the only attribute of the object in the circular array
- wx:key ="*this" means that your array is an 'ordinary array' * this means that it is a circular item
- [1,2,3,4,5]
- ["1","2","3","4"]
- When there is a nested loop of arrays, pay particular attention to the following binding names and do not duplicate them
- wx:for-item="item" wx:for-index="index"
- We don't write by default
- wx:for-item="item" wx:for-index="index"
- The applet will also define the name of the circular item and the name of the index as "item" and "index"
- If there is only one layer of loop (Wx: for item = "item" Wx: for index = "index"), it can be omitted
6. Object loop
- wx:for = "{object}}" wx:for item = "value of object" wx:for index = "attribute of object"
- When looping objects, it's best to change the names of item and index
- wx:for-item="value" wx:for-index="key"
7.block
- Label of placeholder
- You can see the existence of these tags when writing code
- The page rendering applet removes it
8. Conditional rendering
-
wx:if="{{true/false}}"
-
if, else , if else
wx:if
wx:elif
wx: else
-
-
hidden
- Directly add the attribute "hidden" vue on the label, which is v-show
- hidden="{{true}}"
-
Which is used in which scenario
-
When labels are not frequently switched, wx:if is preferred
Remove tags directly from the page structure
-
When the labels are frequently switched, wx:hidden is preferred
By controlling the style display
-
9.input data binding
-
You need to bind the input event to the input tag
Binding keyword bindinput
-
How to get the value of the input box
Get from the event source object
e.detail.value
-
Assign the value of the input box to data
Not directly
1.this.data.num= e.detail.value
2.this.num = e.detail.value
Correct assignment:
this.setData({
num: e.detail.value
})
-
Need to add a click event
- bindtap
- Parameters cannot be passed directly in events in applets
- Pass parameters through custom attributes
<button bindtap="handletap" data-num="{{num}}"></button> bindtap(e){ //Get custom attribute num var num = e.currentTarget.dataset.num //Destructuring assignment var {num} = e.currentTarget.dataset }
10.1 style wxss
The specified screen width is 750rpx
The iPhone 6 has a screen width of 375 px
375px ==750rpx
If there is a design draft 440px or page
440px = 750rpx
Extrapolation evolution
page px = 750rpx
Make use of an attribute, calc attribute, which is supported by css and wxss
Note 750 and rpx Don't leave spaces. Leave space on both sides of the symbol width:calc(750rpx * 100 / 375);
10.2 style import
Use the @ import statement to import an external style sheet. Only relative paths are supported.
@import ".../.../style/common.wxss"
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG tugubva1-1643360178266) (C: \ users \ Hg Huazai \ appdata \ roaming \ typora \ typora user images \ image-20201214151713195. PNG)]
Relative path: relative to the current path, starting from the current path,
10.3 use less
1. Editor vsc plug-in easy less
-
Add the following configuration (p22 set) to the setting of vs code
"less.compile": { "outExt": ".wxss" }
Renaming the wxss file to less and saving it will automatically generate the wxss file
/*1.Define less variable*/ @color: pink; text { color: @color; }
11.view and text
view:
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG ovpzmkff-1643360178269) (C: \ users \ Hg Huazai \ appdata \ roaming \ typora \ typora user images \ image-20201214154113858. PNG)]
text:
1. Only text can be nested
2. Long press to copy (only this tag has this function)
3. You can code the greater than sign, less than sign, enter and space
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-byr6cnje-1643360178270) (C: \ users \ Hg Huazai \ appdata \ roaming \ typora \ typora user images \ image-20201214155055080. PNG)]
12.image
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-1t2cou3j-1643360178271) (C: \ users \ Hg Huazai \ appdata \ roaming \ typora \ typora user images \ image-20201214165757766. PNG)]
1. The default width and height of the picture is 320 * 240
2.mode
3. The pictures in the applet directly support lazy load
1. Lazy load will judge by itself that when the picture appears within the height of the upper and lower three screens of the viewport, it will start loading the picture itself
<image mode="bottom" lazy-load src=""></image>
13.swiper
-
Carousel map outer container swiper
-
Swiper item
-
The default style exists for the wiper label
-
width 100%
-
height 150px image also has a default width height of 320 * 240
-
The height of swiper cannot be supported by content
-
First, find out the width height ratio of the original drawing and set the width height of the swiper
- If the width and height of the original drawing are 1125 * 325px
- swiper width / height = width / height of the original drawing
- Wiper height = wiper width * height of original drawing / width of original drawing
- height: 100vw * 325 /1125
-
mode = "widthFix" of image
-
<swiper> <swiper-item> <image mode="widthFix" src="" /> </swiper-item> <swiper-item> <image mode="widthFix" src="" /> </swiper-item> <swiper-item> <image mode="widthFix" src="" /> </swiper-item> </swiper> swiper { width: 100%; height: calc(100vw * 325 / 1125); } image { width: 100%; }
-
14.navigator
Navigation component navigator
- Block level elements wrap by default, and you can add width and height directly
- url page path to jump absolute path relative path
- Does target want to jump to the current applet or other applets and pages
- self defaults to the page of your applet
- miniProgram other applet pages
- Open type jump mode
- The default value of navigator is to keep the previous page and jump to a page in the application, but it cannot jump to the tabbar page.
- redirect closes the current page and jumps to a page in the application, but cannot jump to the tabbar page.
- switchTab jumps to the tabbar page and closes all other non tabbar pages.
- reLaunch closes all pages and opens to a page in the application
15. Rich text label
html 1.nodes Property 1.Receive tag string, common 2.Receive an array of objects <rich-text nodes="{{html}}"></rich-text>
js page ({ data: { //1. Label string html: '<div class="my_div" style="color:red;"><p>hello</p> </div>' //2. Object array html: [ { //1.div tag is specified by the name attribute name: "div", //2. What are the attributes on the label attrs: { class: "my_div", style: "color: red;" }, //3. The data type to be received by the child node children is consistent with the data type of the second rendering method of nodes children: [ { name: 'p', attrs: {}, //Put text children: [ { type: "text", text: "hello" } ] } ] } ] } })
16.button
[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-cqazc76f-1643360178272) (C: \ users \ Hg Huazai \ appdata \ roaming \ typora \ typora user images \ image-20201215153642403. PNG)]
file: https://developers.weixin.qq.com/miniprogram/dev/component/button.html
Development function of button
[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qrokzatv-1643360178273) (C: \ users \ Hg Huazai \ appdata \ roaming \ typora \ typora user images \ image-2020125154738195. PNG)]
Customer service function: need to go to wechat public platform( https://mp.weixin.qq.com/wxamp/home/guide?lang=zh_CN&token=771833294 )- > Customer Service - > Add micro signal
17.icon
(https://developers.weixin.qq.com/miniprogram/dev/component/icon.html)
18. radio box
- The radio single label must be used with the parent element radio group
- Value the value of the selected radio box
- Bind bindchange event to radio group
<radio-group bindchange="handleChange"> <radio value="male">male</radio> <radio value="female">female</radio> </radio-group> <view> {{gender}}</view>
//js page({ data: { gender: '' }, handleChange(e){ //1. Get the value in the radio box let gender = e.detail.value; //2. Assign the value to the data in data this.setData({ //es6 gender }) } })
19.checkbox
<checkbox-groud bindchange="handleItemChange"> <checkbox value="{{item.value}}" wx:for="{{list}}" wx:key="{{item.id}}">{{item.name}}</checkbox> </checkbox-groud> <viwe>Selected fruit{{checkboxlist}}</view>
page ({ data: { list: [ {id: 0,naem:"Apple", value: "apple"}, {id: 1, name: "Pear", value: "grape"}, {id: 2, name: "Banana", value: "bananer"}, ], checkedlist: [], }, //Check box to select the event handleItemChange(e){ //Gets the value of the selected check box const checkedlist = e.datail.value; //assignment this.setData({ checkedlist }) } })
20. Custom components
The callback function of the component is placed in methods: {}
-
Create component
-
Add a new folder "components" under the directory, and then create the corresponding folder, then right-click and click new Component;
-
At this time, the js file is not page, but component
-
//js file of component Component({ //Property list of the component (to receive data passed from the parent to the child) properties: { }, //Initialization of data data: { }, //Method list of components methods: { } })
-
//json file { "component": true, //The current file is a component "usingComponents": {} //Reference other custom components }
-
-
Declaration component
-
That file uses the json declaration of the component in which file
-
{ "usingComponents":{ //Key value pair "Components": "Component path" "Tabs": "../../components/Tabs/Tabs" //Relative path without suffix } }
-
-
Using components
-
<tabs></tabs>
-
21. Custom tab style
//html <view wx:for="{{tabs}}" wx:key="id" class="title_item {{item.isactive? 'active': ''}}" bindtap="hanldeItemTap" data-index="index" > {{item.name}} </view>
//js Conponenst({ data:{ tabs: [ {id:0,name:'home page',isActive:true}, {id:1,name:'original',isActive:fales}, {id:2,name:'classification',isActive:fales}, {id:3,name:'about',isActive:fales}, ] }, methods: { hanldeItemTap(e){ //Get index const {index} = e.currentTarget.dataset; //Get array in data // let {tabs} = this.data; It's best not to modify this directly Data of data //The most rigorous approach is to make a deep copy of an array and then process the backup of this array let tabs = JSON.parse(JSON.stringify(this.data.tabs)) //Circular array //[]. forEach traverses the array. If v is modified when traversing the array, the original array will also be changed tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false;) //assignment this.setData({ tabs }) } } })
//Applet array deep copy function copyArr(oldArr){ let newArr = []; newArr = JSON.parse(JSON.stringify(oldArr)); return newArr; }
22. Transfer data from parent to child
-
The parent component (page) transmits data to the child component through tag attributes
-
<Tabs aaa="123"> </Tabs>
-
-
Receive on subcomponents
-
Component({ //It stores the data to be received from the parent component (just use prpperties as data) properties: { //Name of the data to receive aaa: { //Type: the type of data to receive type: string, //Value is the default value (if the parent component does not pass a value, this value will be used) value: "" } } })
-
23. Transfer data from child to parent
The transfer of data from a child to a parent is via an event
Add a custom event to the label of the sub component
<Tabs aaa="123" binditemChange="handleItemChange"> </Tabs>
-
When the click event of the sub component is triggered
-
<view bindtap="tabtap"></view>
-
Trigger the custom event of the parent component and pass the data to the parent component at the same time
-
//this. Trigger event ("name of custom event of parent component", parameter to be passed) this.triggerEvent("itemChange",index)
-
components ({ methods: { tabtap(e){ const {index} = e.currentTarget.detaset //If index ==2 this.triggerEvent("itemChange",{index}) } } })
-
page ({ handleItemChang(e){ console.log(e.detail.index) //2 } })
-
24. Custom component - solt
The sole tag is actually a placeholder slot
Wait until the parent component calls the child component, and then pass the tags. Finally, these passed tags will be replaced slot Slot location
//Subcomponents <view> <sole></sole> </view>
The parent component can replace the sole by inserting the label directly
25. Reference life cycle
Global entry file app js
APP({ })
page
Page({ })
assembly
Component({ })
Global lifecycle
APP({ //1. The event that will be triggered when the application is started for the first time onLaunch(){ //Get the user's personal information when the application starts for the first time console.log("onLaunch") }, //2. The application is seen by the user onShow(){ console.log("onshow") }, //3. Application is hidden onHide(){ //Pause or clear timer console.log("hide") }, //4. It will be triggered when an error is reported in the application code onError(err){ //When the application code reports an error, collect the user's error information and send the error information to the background through asynchronous request console.log(err) }, //5. If the page cannot be found, it will be prompted //When the application starts for the first time, it will be triggered if the first entry page cannot be found onPageNotFound(){ console("onPageNotFound"); } })
Component life cycle
26. Local cache
View the storage of the console to view the cache
-
First determine whether there is old data in the local storage
-
{What is the current timestamp like} {time: Date.now(), data: [...]}
-
-
Send a new request directly without old data;
-
If there is old data and the old data has not expired, you can use the old data in the local storage
-
1.Store local data getCates(){ request({ }).then(res=>{ this.Cates = res.data.message; //Store interface data into local storage wx.setStorageSync("cates, {time:Date.now(), data:this.Cates}") }) } 2.Get data from local storage const Cates = wx.getStorageSync("cates"); if(!Cates){ //There is no send request to get data this.getCates(); }
-
The difference between local storage in web and local storage in applet
- The way you write code is different
- web: localStorage.setItem('key','value') ; localStorage.getItem('key')
- Applet: Wx setStorageSync(‘key’, ‘value’); wx.getStorageSync(‘key’);
- Is there any type conversion when saving
- web: no matter what type of data is stored, the following toString() will be called first to change the data into a string and store it
- Applet: there is no type conversion operation. What type of data is stored in it and what type of data is obtained
- The way you write code is different
27. Project notes
1. The domain name needs to be added to the background of the applet;
1.1 development document - > Introduction (click to jump to the wechat public platform wide web home page)( https://mp.weixin.qq.com/ ))->Development - > development settings - > server domain name;
2.: nth last child (- N + 4) / / the next 4
3.less calculation
- height: 33.33vw * 386 / 232 /2;
4.overflow: hidden; zoom: 1; You can also clear the float (the parent element has no height) zoom: 1; For compatibility
5.P15 cat
6. Use of calc
- Pay attention when using calc in less
- height: ~'calc(100vh - 90rpx)';
7. Get "in path"? The latter part will become query,
- App.onLaunch,App.onShow and page The callback function of onload can obtain query data;
8. After the pull-down refresh is successful, close the pull-down refresh page
- wx.PullDownRefresh();
- wx. shopPullDownRefresh(); (VSC: Wx shop will prompt)
9.ios does not support image webp format;
11. Click on the rotating picture to enlarge and preview
- Document - > API - > Picture - > Wx previewImage
12. For applet authorization events, click cancel for the first time, and click No for the second time;
- Get the permission status scope (wx.getSetting({});) authorized by the user to the applet (address, camera...)
- Suppose the user clicks the prompt box of get (receiving address) to confirm authsetting scope The address scope value is true. Call directly to get the receiving address
- Assume that the user has never called the api scope undefined of the receiving address, and directly call to obtain the receiving address
- Suppose the user clicks the prompt box to get the receiving address to cancel the scope value false
- Induce the user to open the authorization setting page (wx.openSetting({})) when the user gives and obtains the address permission again
- Get address
13. Use [] only when the attribute name is weird
-
result.authSetting["scope.address"]
14. Get the parameters passed from the previous page
-
Pages using applets
-
Get the page number of the current applet - the maximum length of the array is 10 pages
-
The largest page in the index in the array is the current page
-
let pages = getCuttentPages(); //Pages = > array of all pages let currentPage = pages[pages.length-1]; //The largest index of the array;
-
15.vsc entering lorem will display text that is very similar to the length of the text,
16. One or more lines exceed the display ellipsis
-
One line exceeds the display ellipsis;
-
overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
-
-
Multiple lines display ellipsis;
-
overflow: hidden; display: -webkit-box; //The object must be displayed as an elastic box model in combination with the properties of. -webkit-box-orient: vertical;//The arrangement of the child elements of the expansion box object must be set or retrieved in combination with the properties of the -webkit-line-clamp: 3; //Used to limit the number of lines of text displayed in a block element
-
17. Remove the spaces on both sides
-
value.trim()
18. Anti shake (anti shake) timer throttling
-
The anti shake general input box prevents repeated input and repeated sending requests
-
Throttling is generally used for page pull-up and pull-down (pull-up refresh and pull-down load)
-
pages {( data:{ }, //Define global timer TimeId: -1, //An event triggered when the value of the input box changes handleInput(e){ //1. Get the value of the input box const {value} = e.detail; //2. Check the validity (whether the spaces on both sides of the input box have values) if(!value.trem()){ //Illegal value return; } //Clear timer clearTimeout(this.TimeId); //3. Prepare to send request for data this.TimeId = setTimeout(()=>{ this.qsearch(value); //Initiate request },1000) } )}