WeChat applet uses uni-app to develop applets and some functions to achieve detailed experience

Table of contents

1. uni-app

1 Introduction

2. Development tools

3. Create a new uni-app project

4. Run the project to the WeChat developer tool

2. Realize the tabBar effect

1. Create a tabBar page

2. Configure tabBar

1. Create a subpackage directory

2. Configure in the pages.json file

3. Create a subpackage page

4. Public method encapsulation

5. Search function

1. Search component

2. Implementation of search suggestions

3. Local storage

4. Filter

6. Pull up to load, pull down to refresh

1. Pull-up loading

2. Pull down to refresh

7. Login

1. Obtain basic user information

2. Obtain the user login credential code

8. Payment

1. Add token to the request header

2. WeChat payment process

other

Summarize


1. uni-app

Official website: uni-app official website

1 Introduction

uni-app is a framework for developing all front-end applications using Vue.js (opens new window). Developers write a set of codes that can be published to iOS, Android, Web (responsive), and various small programs (WeChat/Alipay /Baidu/Toutiao/Feishu/QQ/Kuaishou/DingTalk/Taobao), Quick App and other platforms;

2. Development tools

uni-app recommends using Hbuilderx development tools to develop projects, download address: HBuilderX-Efficient Geek Skills or click here to download , download the App development version;

1. Install the sass plugin

Click  Tools => Plug-in Installation => Install New Plug-ins => Go to the Plug-in Market to install  , here you can search for the plug-ins you need, let's take sass as an example; after finding the plug-ins you need, click Download => Use Hbuilderx to import the plug-ins , here you need Log in to the sass website, if the login is successful, the Hbuilderx compiler will be opened, and then click OK to install it;

3. Create a new uni-app project

Hbuilderx Click  File => Add => Project  , this article creates a new small program project: uni-app => fill in the project name, select the project storage path => template uni-ui project => create, and then you can generate a small program project ;

components: component file
pages: page file
static: static file
uni_modules: dependent package
App.vue: application configuration, configuration of applet global style, life cycle
main.js: Vue initialization entry file
manifest.json: configuration application name appid, logo, Version and other packaging information
pages.json: configuration page path, page style, tabBar and other information
uni, scss: global style

4. Run the project to the WeChat developer tool

1. Configure appid

 Fill in the WeChat applet appID in  the manifest.json file => WeChat applet configuration ;

2. Configure the installation path of WeChat developer tools in Hbuilderx: so that you can automatically open the WeChat developer tools to view the project when running in Hbuilderx

Tools => Settings => Run Configuration => Mini Program Run Configuration  Configure the installation path of WeChat developer tools, such as: C:\Program Files (x86)\Tencent\WeChat web developer tools

3. Open the service port in the WeChat developer tool

Settings => Security Settings => Safely  open the service port

4. Run

Click on Hbuilderx to  run => run to the Mini Program Simulator  and click the first one to automatically compile in Hbuilderx. After success, it will automatically open the WeChat developer tool;

Note : At this time, if we want to modify the content of the project, we need to modify it in Hbuilderx, such as modifying the configuration: manifest.json file => source view

2. Realize the tabBar effect

1. Create a tabBar page

Create under pages, right-click to create a new page, here are several pages corresponding to tanBar; remember to check the two options of "create directory with the same name, register in pages.json", which are selected by default; (home, cate, cart, my)

2. Configure tabBar

Add tabBar configuration at the pages level in the pages.json file:

"tabBar":{
	"selectedColor":"#C00000",
	"list":[
		{
			"pagePath":"pages/home/home",
			"text":"首页",
			"iconPath":"static/c1.png",
			"selectedIconPath":"static/c2.png"
		},
		{
			"pagePath":"pages/cate/cate",
			"text":"分类",
			"iconPath":"static/c3.png",
			"selectedIconPath":"static/c4.png"
		},
		{
			"pagePath":"pages/cart/cart",
			"text":"购物车",
			"iconPath":"static/c5.png",
			"selectedIconPath":"static/c6.png"
		},
		{
			"pagePath":"pages/my/my",
			"text":"我的",
			"iconPath":"static/c7.png",
			"selectedIconPath":"static/c8.png"
		}
	]
}

Note : home must also be the first in the pages array; you can also modify the globalStyle configuration item in the pages.json file to customize your own navigation bar style;

3. Small program subcontracting in uni-app

1. Create a subpackage directory

Create a subpackage directory, subpackage, under the root directory;

2. Configure in the pages.json file

At the same level as the pages node, declare the subpackages node to configure the subpackage structure;

"subPackages":[
	{
		"root":"subpackage",
		"pages":[]
	}
]

3. Create a subpackage page

Right click on the new file in the sunpackage directory , fill in the page name, select subpackage sunpackage, and then create it. The compiler will automatically fill the configuration information under the sunpackage subpackage in the code;

"subPackages":[
		{
			"root":"subpackage",
			"pages":[{
                    "path" : "goods_detail/goods_detail",
                    "style" :{
	                    "navigationBarTitleText": "",
	                    "enablePullDownRefresh": false
	                }
                }
            ]
		}
	]

Note : It is mentioned here that page redirection and parameter passing are the same as those of the applet’s native redirection: 1. The navigator cooperates with url jumping and path splicing to pass parameters; 2. The click event passes through uni.redirectTo;

4. Public method encapsulation

Here, take the error message as an example, in main.js;

uni.$showMsg = function(titie="request failed",duration=1000){ 
	uni.showToast({ 
		title, 
		duration, 
		icon:"none" 
	}) 
}

5. Search function

1. Search component

1. Customize the search component: right click on the components folder, select  New Component  , where you can write the content of the component;

2. Mini Program custom components Custom events: Since the components provided by the Mini Program have helped us encapsulate the click event, we can use it directly, but our custom components are not encapsulated, so we cannot directly use click on the custom components event;

We can bind a custom event to the parent component, then bind the click event to the child component, and use $emit to trigger the custom event bound to the parent component when the click is triggered, so that the event delivery of the custom component can be completed;

3. Ceiling: mainly use position:sticky to position the component to the top of the page;

Finally, use the component : it can be used directly on the page, and the component name is the file name of the custom component;

//自定义组件
<template>
	<view class="my-search-container" :style="{'background-color':bgColor}">
		<view class="my-search-box" :style="{'border-radius':radius}">
			<uni-icons type="search" size="18"></uni-icons>
			<text class="placeholder">搜索</text>
		</view>
	</view>
</template>
<script>
	export default {
		name:"my-search",
		props:{
			bgColor:{
				type:String,
				default:"#c00000"
			},
			radius:{
				type:String,
				default:"18px" 
			searchEvent(){
			//Through $emit to trigger the custom event bound on the parent component
		methods:{
		},
			}
				this.$emit('myclick')
			}
		}
	}
</script>
<style lang="scss">
.my-search-container{
	height: 50px;
	// background-color: #c00000;
	display:flex;
	align-items: center;
	padding: 0 10px;
	.my-search-box{
		height: 36px;
		background-color: #FFF;
		// border-radius: 18px;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		.placeholder{
			font-size: 15px;
			margin-left: 5px;
		}
	}
}
</style>
//父组件
<template>
	<view>
		<view class="suckTop">
			<my-search @myclick="goSearch" :radius="'0px'" :bgColor="'pink'"></my-search>
		</view>
	</view>
</template>
<script>
	export default {
		methods:{
			goSearch(){
				uni.navigateTo({
					url:"/subpackage/search/search"
				})
			}
		}
	}
</script>
<style lang="scss">
.suckTop{
	position: sticky;
	top: 0;
	z-index: 999;
}
</style>

2. Implementation of search suggestions

<template>
	<view>
		<view class="suckTop">
			<uni-search-bar @input="input" :radius="18" :focus="true" cancelButton="none"></uni-search-bar>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				timer:null,
				kw:''
			}
		},
		methods: {
			//输入框事件
			input(e){
				clearTimeout(this.timer)
				this.timer = setTimeout(_=>{
					this.kw = e.value;
				},500)
			},
		}
	}
</script>
<style lang="scss">
.suckTop{
	position: sticky;
	top: 0;
	z-index: 999;
	.uni-searchbar {
		background-color: #c00000
	}
}
</style>

Use the components provided by uni-app, add focus to let the interface automatically lock the input box, add throttling to the input event, and then call the interface in the throttling method to obtain and render the search results;

3. Local storage

//Save 
uni.setStorageSync('kw',JSON.stringify(this.kw)); 

//take let list in the onLoad statement cycle 
= JSON.parse(uni.getStorageSync('kw') || ''); 

/ /delete 
uni.setStorageSync('kw',[]);

4. Filter

Declare filters at the same level as data

filters:{
	toFixed(num){
		return Number(num).toFixed(2);
	}
}

directly on the interface when using

<view>{
  
  {num | toFixed}}</view>

6. Pull up to load, pull down to refresh

1. Pull-up loading

Find the path of the current page in the pages array in pages.json, and add onReachBottomDistance to 150 in the style;

Declare an onReachBottom method at the level of methods in the page to listen to the page pull-up event;

data() { 
	return { 
		isLoading:false 
	}; 
}, 
methods:{ 
	getList(){ 
		//Open throttle 
		this.isLoading = true; 
		//Get data 
		let res = ..... 
		//Close throttle 
		this.isLoading = false; 
	} 
}, 
//Listen to the pull-up event 
onReachBottom() { 
	//No more data 
	if(this.pagenum*this.pagesize >= this.total) return uni.$showMsg('No more Data') 
	//Limit current to prevent frequent requests 
	if(this.isLoading) return; 
	//The page is self-increased by 
	this.pagenum++; 
	//The method of obtaining list data 
	this.getList(); 
}

2. Pull down to refresh

Find the path of the current page in the pages array in pages.json, add enablePullDownRefresh in style and set it to true;

Declare an onPullDownRefresh method in the method level of the page to listen to the page pull event;

methods:{ 
	getList(cb){ 
		//Open throttle 
		this.isLoading = true; 
		//Call callback function 
		cb && cb(); 
		//Get data 
		let res = ..... 
		//Close throttle 
		this .isLoading = false; 
	} 
}, 
onPullDownRefresh() { 
	this.total = 0; 
	this.pagenum = 1; 
	this.list = []; 
	this.isLoading = false; 
	// Pass in the callback function to stop the pull-down refresh effect 
	this. getList(()=> uni.stopPullDownRefresh()); 
}

7. Login

Before calling the login interface, we need to obtain the user's basic information and code as parameters;

1. Obtain basic user information

<button open-type="getUserInfo" @getuserinfo="getInfo">One-click login</button> 
methods:{ 
	//Custom method 
	getInfo(e){ 
		console.log(e) 
	} 
}

The open-type provided by the button component is directly used here, which is equal to getUserInfo, and the user information is obtained from the @getuserinfo event binding method; here is the fixed writing method; refer to the official website: button | uni-app official website

2. Obtain the user login credential code

This can directly call the uni.login() API;

async getCode(){
	let [err,res] = await uni.login().catch(err=>err)
	console.log(res)
}

8. Payment

1. Add token to the request header

Only after the login is successful can the payment-related interface be called. We need to set the token obtained after login in the authorized interface request field; generally, the header is uniformly configured for the interface in the request interception;

$http.beforeRequest = function (options) { 
  uni.showLoading({ 
  	title: "Data loading..." 
  }) 
  options.header = { 
	  Authorization: token 
  } 
}

2. WeChat payment process

1. Create an order

Submit the order information to the background server, create an order, and obtain the order number;

2. Order prepayment

Send the order number to the background server to obtain payment-related parameters;

3. Call WeChat payment

Call the uni.requestPayment(OBJECT) API to initiate a payment request; monitor whether the payment is successful through the fail and success callback functions, and then call the background interface to synchronize the payment status to the database;

other

Here are some of the more common components, APIs, and issues:

1、API:uni.previewImage(OBJECT)

To preview the picture, you can use the carousel method to view it;

2、API:uni.chooseAddress(OBJECT)

Get the user's shipping address. Invoke the user's native interface for editing the delivery address, and return the address selected by the user after editing, requiring the user to authorize scope.address;

3. Component: rich-text

render rich text;

4. Component: uni-goods-nav

Add the product to the shopping cart and buy the component immediately;

5. Problem: The .webp suffix image does not display the problem on ios

The .webp format support for pictures on ios is not very friendly, you can replace the picture suffix with .jpg as long as the regular expression is needed;

6. Problem: Commodity price flickering problem

Before the data is requested to the page, the data in data is initially {}, so the initial rendering will cause some data to flicker. You can first use v-if to judge whether the data exists to control the display and hiding of the overall interface;

7. Problem: Harvest address authorization failure problem

Determine whether it is an authorization failure problem, and if so, directly call the uni.openSetting(OBJECT) API to open the address permission; note that it is compatible with ios and Android;

Summarize

This is the end of this article about using uni-app to develop applets for WeChat applets and the realization of some functions. For more information about using uni-app to develop applets for WeChat applets, please search previous articles or Continue to browse the relevant articles below and hope that you will support developpaer a lot in the future!

Guess you like

Origin blog.csdn.net/Fang2001131919/article/details/131296090