WeChat applet - use uni-app to develop applets and implement some functions

1. uni-app

Official website: https://uniapp.dcloud.io/

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: https://www.dcloud.io/hbuilderx.html , download the App development version;

1. Install the sass plug-in
Click Tools => Plug-in Installation => Install New Plug-in => Go to the plug-in market to install , where you can search for the plug-in you need, let's take sass as an example; after finding the plug-in you need, click Download => Use Hbuilderx Import the plug-in . Here you need to 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 ;
insert image description here

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 the appid
in the manifest.json file => WeChat Mini Program Configuration Fill in the WeChat Mini Program appID;

2. Configure the installation path of WeChat developer tools in Hbuilderx: In this way, you can automatically open the WeChat developer tools when running in Hbuilderx View project tools => Settings => Run configuration => Mini program
run configuration Configure the installation of WeChat developer tools Path, such as: C:\Program Files (x86)\Tencent\WeChat web developer tools

3. Open the service port setting in WeChat Developer Tools
=> Security Settings => Security to open the service port

4. Run
Hbuilderx Click Run => Run to Mini Program Simulator Click the first one to automatically compile in Hbuilderx, and it will automatically open the WeChat developer tool after success;

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. Configure network requests

Since the mini program does not support axios, and the original wx.request() API function is relatively simple, and does not support global customization functions such as interceptors; it is recommended to use the @escook/request-miniprogram third-party package in the uni-app project to initiate network request;

Official website: https://www.npmjs.com/package/@escook/request-miniprogram

1. Follow the instructions on the official website to install, import and use

//引入网络请求
import {
    
     $http } from '@escook/request-miniprogram';
uni.$http = $http;
//全局baseUrl
$http.baseURL = "https://www.uinav.com";
//请求拦截器
$http.beforeRequest = function (options) {
    
    
  uni.showLoading({
    
    
  	title:"数据加载中..."
  })
}
//相应拦截器
$http.afterRequest = function () {
    
    
  uni.hideLoading()
}

In uni-app, you can use uni.xxx to call the api of wx.xxx;

2. Actual combat

//home
data() {
    
    
	return {
    
    
		swiperList:[]
	};
},
onLoad() {
    
    
	this.getSwiperList();
},
methods:{
    
    
	async getSwiperList(){
    
    
		let {
    
     data:res } = await uni.$http.get('接口地址')
		if(res.meta.status !== 200){
    
    
			return uni.showToast({
    
    
				title:"数据请求失败",
				duration:1500,
				icon:"none"
			})
		}
		this.swiperList = res.message;
	}
}

4. 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 : Let me mention 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;

5. Public method encapsulation

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

uni.$showMsg = function(titie="请求失败",duration=1000){
    
    
	uni.showToast({
    
    
		title,
		duration,
		icon:"none"
	})
}

6. 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"
			}
		},
		methods:{
    
    
			//通过 $emit 来触发父组件上绑定的自定义事件
			searchEvent(){
    
    
				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

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

//onLoad 声明周期中 取
let list = JSON.parse(uni.getStorageSync('kw') || '');

//删除
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>

Seven, 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(){
    
    
		//打开节流阀
		this.isLoading = true;
		//获取数据
		let res = .....
		//关闭节流阀
		this.isLoading = false;
	}
},
//监听上拉事件
onReachBottom() {
    
    
	//没有更多数据
	if(this.pagenum*this.pagesize >= this.total) return uni.$showMsg('没有更多数据了')
	//限流 防止频繁请求
	if(this.isLoading) return;
	//页面自增加一
	this.pagenum++;
	//获取列表数据的方法
	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){
    
    
		//打开节流阀
		this.isLoading = true;
		//调用回调函数
		cb && cb();
		//获取数据
		let res = .....
		//关闭节流阀
		this.isLoading = false;
	}
},
onPullDownRefresh() {
    
    
	this.total = 0;
	this.pagenum = 1;
	this.list = [];
	this.isLoading = false;
	//传入回调函数,停止下拉刷新效果
	this.getList(()=> uni.stopPullDownRefresh());
}

Eight, configure vuex

1. Create a file

Create a folder store in the root directory, and create a file store.js under the folder;

2. Initialize store

//store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
import cart from '@/store/cart.js'
const store = new Vuex.Store({
    
    
	modules:{
    
    
		cart
	}
})
export default store;

3. Introduced in main.js

//main.js
import store from './store/store.js'
const app = new Vue({
    
    
    ...App,
    //挂载到vue实例上
	store
})
app.$mount()

4. Create a new module

Create a new js file of the cart module, and then import it into store.js;

//cart.js
export default {
    
    
	namespaced:true,
	state:{
    
    
		cart:[]
	},
	//修改state 只能通过 mutations 
	mutations:{
    
    
		addCart:(state,data)=>{
    
    
			state.cartList.push(data)
		}
	},
	getter:{
    
    }
}

5. use

import {
    
     mapState, mapActions, mapMutations } from 'vuex';

computed:{
    
    
	...mapState({
    
    
		cartList:state=>state.cart.cartList
	})
},
methods: {
    
    
	...mapMutations(['addCart']),
	addCartInfo(){
    
    
		this.addCart(2)
		// this.$store.commit('addCart',2)
	},
	//输入框事件
	input(e){
    
    
		clearTimeout(this.timer)
		this.timer = setTimeout(_=>{
    
    
			this.kw = e.value;
		},500)
	}
	}

9. 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">一键登录</button>
methods:{
    
    
	//自定义方法
	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 through the @getuserinfo event binding method; here is the fixed writing method; refer to the official website: https://uniapp.dcloud.io/component/button . html

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

10. 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:"数据加载中..."
  })
  options.header = {
    
    
	  Authorization: token
  }
}

2. WeChat payment process

1. Create an order
Submit the order information to the background server, create the 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
to call 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;

11. Release

Applets can be retrieved and used by users only after they are released. During development, for debugging purposes, applets will carry sourcemap and other types of files, and the code is not compressed, so the size is relatively large, so it needs to be compressed and released;

1. Publish as a small program

1. Click Publish on => Mini Program-WeChat . At this time, there will be a pop-up box where you need to fill in the name and AppID of the Mini Program;
2. Click the Release button, and the hbuilderx console will display the progress of packaging and compiling;
3. After the compilation is successful, the WeChat developer tool will be automatically released, and click the upload button at this time;
4. Then some prompt information will pop up, click OK, and a pop-up window of version number and project notes will pop up, just click upload;
5. Then WeChat small The background audit of the program can be launched;

2. Publish as an Android APP

1. Click the lower left corner of hbuilderx to log in without logging in, and log in with the account;
2. After logging in, click the manifest.js file of the project, and in the basic configuration, fill in the AppID, application name, description, version, etc. of the uni-app; 3.
App icon configuration, Preview and select the picture, and then automatically generate the configuration;
4. Click on the hbuilderx toolbar Release => Native App-Cloud Packaging , and then a pop-up window will pop up to select the Android apk package. For iOS, you need to purchase a developer identity before packaging, and use a public test certificate. Check the official package, and then click package; 5. Then the packaging progress will be displayed on the hbuilderx console. After success, a link to the download address
will be returned. Click the link to download the apk installation package. This apk package can be installed on the Android system Installed and checked;

other

The following are some common components, APIs, and problems:
1. API: uni.previewImage(OBJECT)
to preview pictures, you can view the carousel image;
2. API: uni.chooseAddress(OBJECT)
to obtain the user's delivery address. Call the original interface for users to edit the delivery address, and return to the address selected by the user after the editing is completed, the user needs to authorize scope.address; 3.
Component: rich-text
rendering rich text;
4. Component: uni-goods-nav
commodity added Shopping cart, buy components immediately;
5. Problem: The .webp suffix image does not display on ios.
The .webp format of the image on ios is not very friendly. You can replace the image suffix name with .jpg as long as the regular expression;
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 this data exists to control the display and hiding of the overall interface; 7
. Question: Harvesting address authorization failure problem
Judging whether it is an authorization failure problem, if so, directly call uni.openSetting(OBJECT) API to open the address permission; note that it is compatible with ios and Android;

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/123852298