Basic introduction notes of wechat applet development

Posted by dodgeqwe on Sat, 29 Jan 2022 08:17:04 +0100

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

structureTraditional webWechat applet
structureHTMLWXML
styleCSSWCSS
logicJavascriptJavascript
to configureJSON

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

  1. 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
  2. The window field defines all the top background colors and text color definitions of the applet
//app.json
{
 "pages":{
 
 },
 "window":{
 
 }
}

4. Operation = > expression

  1. You can add the expression - "statement" in curly braces

  2. expression

    It refers to some simple operations, numerical operations, string splicing, logical operations...

    1. Addition and subtraction of numbers
    2. String splicing
    3. Ternary expression
  3. sentence

    1. Copied code snippet
      1. if else
      2. switch
      3. do while ...
      4. for ...
  4. {{1+2}}     //3
    

5. List cycle

  1. wx:for = "{{array or object}}" wx:for item = "name of circular item" wx:for index = "index of circular item"
  2. wx:key = "unique value" is used to improve the performance of list rendering
    1. When wx:key binds an ordinary string, the name of the string must be the only attribute of the object in the circular array
    2. wx:key ="*this" means that your array is an 'ordinary array' * this means that it is a circular item
      1. [1,2,3,4,5]
      2. ["1","2","3","4"]
    3. When there is a nested loop of arrays, pay particular attention to the following binding names and do not duplicate them
      1. wx:for-item="item" wx:for-index="index"
    4. We don't write by default
      1. wx:for-item="item" wx:for-index="index"
      2. The applet will also define the name of the circular item and the name of the index as "item" and "index"
      3. If there is only one layer of loop (Wx: for item = "item" Wx: for index = "index"), it can be omitted

6. Object loop

  1. wx:for = "{object}}" wx:for item = "value of object" wx:for index = "attribute of object"
  2. When looping objects, it's best to change the names of item and index
    1. wx:for-item="value" wx:for-index="key"

7.block

  1. Label of placeholder
  2. You can see the existence of these tags when writing code
  3. The page rendering applet removes it

8. Conditional rendering

  1. wx:if="{{true/false}}"

    1. if, else , if else

      wx:if

      wx:elif

      wx: else

  2. hidden

    1. Directly add the attribute "hidden" vue on the label, which is v-show
    2. hidden="{{true}}"
  3. Which is used in which scenario

    1. When labels are not frequently switched, wx:if is preferred

      Remove tags directly from the page structure

    2. When the labels are frequently switched, wx:hidden is preferred

      By controlling the style display

9.input data binding

  1. You need to bind the input event to the input tag

    Binding keyword bindinput

  2. How to get the value of the input box

    Get from the event source object

    e.detail.value

  3. 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

    ​ })

  4. Need to add a click event

    1. bindtap
    2. Parameters cannot be passed directly in events in applets
    3. 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

  1. 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

  1. Carousel map outer container swiper

  2. Swiper item

  3. The default style exists for the wiper label

    1. width 100%

    2. height 150px image also has a default width height of 320 * 240

    3. The height of swiper cannot be supported by content

    4. First, find out the width height ratio of the original drawing and set the width height of the swiper

      1. If the width and height of the original drawing are 1125 * 325px
      2. swiper width / height = width / height of the original drawing
      3. Wiper height = wiper width * height of original drawing / width of original drawing
      4. height: 100vw * 325 /1125
    5. mode = "widthFix" of image

    6. <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

  1. Block level elements wrap by default, and you can add width and height directly
  2. url page path to jump absolute path relative path
  3. Does target want to jump to the current applet or other applets and pages
    1. self defaults to the page of your applet
    2. miniProgram other applet pages
  4. Open type jump mode
    1. 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.
    2. redirect closes the current page and jumps to a page in the application, but cannot jump to the tabbar page.
    3. switchTab jumps to the tabbar page and closes all other non tabbar pages.
    4. 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

  1. The radio single label must be used with the parent element radio group
  2. Value the value of the selected radio box
  3. 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: {}

  1. Create component

    1. Add a new folder "components" under the directory, and then create the corresponding folder, then right-click and click new Component;

    2. At this time, the js file is not page, but component

    3. //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: {
      	
      	}
      })
      
    4. //json file
      {
          "component": true,     //The current file is a component
          "usingComponents": {}   //Reference other custom components
      }
      
  2. Declaration component

    1. That file uses the json declaration of the component in which file

    2. {
      	"usingComponents":{
      	//Key value pair
      	"Components": "Component path"
      	"Tabs": "../../components/Tabs/Tabs"    //Relative path without suffix
      	}
      }
      
  3. Using components

    1. <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

  1. The parent component (page) transmits data to the child component through tag attributes

    1. <Tabs  aaa="123"> </Tabs>
      
  2. Receive on subcomponents

    1. 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>
  1. When the click event of the sub component is triggered

    1. <view bindtap="tabtap"></view>
      
    2. Trigger the custom event of the parent component and pass the data to the parent component at the same time

    3. //this. Trigger event ("name of custom event of parent component", parameter to be passed)
      
      this.triggerEvent("itemChange",index)
      
    4. components ({
      	methods: {
              tabtap(e){
                  const {index} = e.currentTarget.detaset    //If index ==2
                  this.triggerEvent("itemChange",{index})
              }
          }
      })
      
    5. 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

  1. First determine whether there is old data in the local storage

    1. {What is the current timestamp like}
      {time: Date.now(), data: [...]}
      
  2. Send a new request directly without old data;

  3. If there is old data and the old data has not expired, you can use the old data in the local storage

  4. 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();
    }
    
  5. The difference between local storage in web and local storage in applet

    1. The way you write code is different
      1. web: localStorage.setItem('key','value') ; localStorage.getItem('key')
      2. Applet: Wx setStorageSync(‘key’, ‘value’); wx.getStorageSync(‘key’);
    2. Is there any type conversion when saving
      1. 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
      2. Applet: there is no type conversion operation. What type of data is stored in it and what type of data is obtained

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

  1. 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

  1. Pay attention when using calc in less
  2. height: ~'calc(100vh - 90rpx)';

7. Get "in path"? The latter part will become query,

  1. 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

  1. wx.PullDownRefresh();
  2. 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

  1. Document - > API - > Picture - > Wx previewImage

12. For applet authorization events, click cancel for the first time, and click No for the second time;

  1. Get the permission status scope (wx.getSetting({});) authorized by the user to the applet (address, camera...)
    1. 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
    2. Assume that the user has never called the api scope undefined of the receiving address, and directly call to obtain the receiving address
    3. Suppose the user clicks the prompt box to get the receiving address to cancel the scope value false
      1. Induce the user to open the authorization setting page (wx.openSetting({})) when the user gives and obtains the address permission again
      2. Get address

13. Use [] only when the attribute name is weird

  1. result.authSetting["scope.address"]
    

14. Get the parameters passed from the previous page

  1. Pages using applets

    1. Get the page number of the current applet - the maximum length of the array is 10 pages

    2. The largest page in the index in the array is the current page

    3. 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

  1. One line exceeds the display ellipsis;

    1. overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      
  2. Multiple lines display ellipsis;

    1. 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

  1. value.trim()
    

18. Anti shake (anti shake) timer throttling

  1. The anti shake general input box prevents repeated input and repeated sending requests

  2. Throttling is generally used for page pull-up and pull-down (pull-up refresh and pull-down load)

  3. 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)
        }
    )}
    

Topics: Front-end Mini Program