uniapp develops WeChat applet/h5 complete process, including vant/uview (h5 adapts to vw)


theme: smartblue
highlight: dark


create project

insert image description here

Created project
insert image description here

insert a hole here
insert image description here

You can also use uniapp vue-cli to create projects

vue create -p dcloudio/uni-preset-vue my-project

Use vue3/vite to create a project (if the command line creation fails, please visit gitee directly to download the template)

npx degit dcloudio/uni-preset-vue#vite my-vue3-project

The created directory is as follows ( uview framework does not support vue3 )
insert image description here

To run the project, use yarn dev:mp-weixin
to open the applet development tool and import the packaged dist package. The weixin package can be used in the development tool, and the package release is the same

HubilderX already supports vue3 to create templates

insert image description here

  • As shown in the figure above, after clicking the new project in the upper left corner, there is a Vue version option in the lower right corner, the default is 2, you can choose 3
  • The project created after selecting version 3 is the same as vue2 but can use setupthe syntax
  • There is no this point in vue3, so you need to introduce syntax such as import {onShow} from '@dcloudio/uni-app'
    **The following is a demo example**


** The console information is as follows. We know that using vite to compile means that we can start compiling and packaging faster. For specific comparisons between webpack and vite, please refer to the official website. It is recommended to save the picture and upload it directly (img-cHDfH4Bn-1660528771028) (https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/118e6b32b2ae4a84915d911c6c1562a5~tplv-k3u1fbpfcp-watermark.image?)]

Use the u-view framework ( uview framework does not support vue3 temporarily )

1. Open the terminal and enter the code. npm install uview-uiFor details, refer to the official website u-view

2. Introduce global uView

import uView from 'uview-ui'
Vue.use(uView)
//使用rpx
uni.$u.config.unit = 'rpx'

3. Referenced in uni.scss @import 'uview-ui/theme.scss';

4. Configure easycom component mode in pages.json

"easycom": {
    // npm安装的方式不需要前面的"@/",下载安装的方式需要"@/"
    "^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"
    // "^u-(.*)": "@/uview-ui/components/u-$1/u-$1.vue"
},

After restarting HBuilderX, the UI framework has been introduced into the project

use vuex

Using vuex in uniapp

在src目录下新建一个store文件件, 在store文件夹下创建index.js
此处我使用了vuex-persistedstate 保持数据的持久化插件
命令行:   npm install --save vuex-persistedstate
然后跟vue中一样创建store在main.js中挂载
下面上代码

insert image description here

store/index.js

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-oatFC9je-1660528771029)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /c05977c1ff564718a3020bbf9a75d3d9~tplv-k3u1fbpfcp-watermark.image?)]

main.js

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-zq7mVouE-1660528771029)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /12df1da9da7a4c7f8cb4b8331cb65546~tplv-k3u1fbpfcp-watermark.image?)]

official development

configuration page

Create a new page, register it in page.json, and set the status bar and other information (refer to the uniapp official website for details)

	{
			"path": "pages/index/index",
			"style": {
				"navigationBarTitleText": "主页",
				"navigationBarBackgroundColor":"#fff",
				"navigationStyle":"default",
				"navigationBarTextStyle":"black",
				"enablePullDownRefresh":false,
			}
		}

Configure tarbar official website tarbar

"tabBar": {
 	"list": [{
 		"pagePath": "pages/index/index",
 		"text": "home"
 	}]
 },

Use the ui framework uview

It is known that uview has two installation methods (npm configuration, ### Hbuilder configuration) with similar methods, and the npmp configuration download method configuration
is not shown here

use vant

Download vant applet source address vant-weapp: Lightweight and reliable widget UI component library vant-weapp: Lightweight and reliable widget UI component library

First create the wxcomponents/vant directory in the src directory

Put the downloaded source dist package "content" in the vant directory again (note that it is not the dist folder but the component folder in the dist package)

Here is to use the easycom mechanism of uniapp to automatically introduce components

Pay attention to the directory structure so that there is no need to use usingComponents, it will automatically register for us after compilation

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Dye1ImUM-1660528771029)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /c8f6e03051064791855399943707509b~tplv-k3u1fbpfcp-watermark.image?)]

Add in app.vue

<style>
/*每个页面公共css */
@import "/wxcomponents/vant/common/index.wxss";
</style>

Add in page.json

 "easycom": {
        "custom": {
            "^van-(.*)": "@/wxcomponents/vant/$1/index"
        }
    },

Finally, you can use the component directly in the required page

<van-button type="danger">危险按钮</van-button>

Finally, if the applet is released, unused components can be deleted to reduce the size of the package

Custom tarbart, navigation bar

1-1. The original tarbar needs to be hidden in App.vue onShow

uni.hideTabBar()

1-2. To create a common component, you can use the tarbar component in u-view or customize the style of the component, and use it directly on the page

easycomIt is automatically turned on and does not need to be turned on manually.
You only need to create the same name in the components directory, and it is components/组件名称/组件名称.vuea directory structure, so you don’t need to reference the registration point on the page. I view the official website address

u-view tarbar component

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-BLX0gm6Z-1660528771030)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /7946096585654940b9e878f39d0833e2~tplv-k3u1fbpfcp-watermark.image?)]

I will not show the specific business logic and page UI here

2-1. Set the page style in page.json "navigationStyle": "custom"to remove the original style

2-2. Introduce a custom navigation bar component into the page to use it, as shown in the figure above (
u-view navbar component )

When using custom components, you need to pay attention to the bottom height of models above iphonex

.box { padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom); }

If you change the u-view component style, you need to pay attention to two points.
Click to view the official website details

v-deep3-1. Generally pass or /deep/order modification in app and h5

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-6gMe53nw-1660528771031)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /446333657a1743c7abd8d32d39d8fe40~tplv-k3u1fbpfcp-watermark.image?)]

3-2. In the WeChat applet, it needs to be changed under the class name of the parent component

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-pRUOI3Cm-1660528771031)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /025156c673f844a693cb0a1ed20dfd6d~tplv-k3u1fbpfcp-watermark.image?)]

The component class name is .navbar Wechat applets must use /deep/
insert image description here

login process

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NnGlE3wf-1660528771033)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /858ef93a4c4749058623b898d76c3331~tplv-k3u1fbpfcp-watermark.image?)]

The picture above is the official login diagram of the WeChat Mini Program

use uni.login

From the figure above, we can see that we need to get the login status with the code returned by uni.login()

Open manifest.json Open the WeChat applet to set the appid and the appid needs to be consistent with the backend appid

The backend and the WeChat server request the openid and session_key, and the backend can customize the login status at this time

Let me talk about my login page process.
On the home page, it is judged whether there is local information after login, such as user information, token, etc. I use the user’s mobile phone to store locally.

If there is no local information, jump to the login page, the user clicks the button to log in and update the user information, and then returns to the home page to load other information

Existing information locally, execute uni.login() to update the token to prevent the user token from expiring, it is best to write it in onload(), you don’t need to log in every time

Get user information

The use of uni.getUserProfile() must be obtained under the click event to obtain getUserInfo to obtain anonymous data, which cannot be used
and can only obtain user nickname and avatar information, and other information cannot be obtained

User authorization is required for each click

get mobile number

I have used both methods. Currently I am using the first method. The second method needs to obtain the code of uni.login separately and pass it to the backend.

1. Use the getPhoneNumber interface. This method must be an address that has been authenticated by the applet

insert image description here

The value returned by the getphonenumber method is shown in the figure below

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-XKZw4NkY-1660528771034)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /5203afd9f5334f8489343114b43e43dc~tplv-k3u1fbpfcp-watermark.image?)]

The backend can obtain the code (dynamic token) to log in and decrypt the mobile phone number at the backend. The specific method is as follows :

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-VNO1keHI-1660528771034)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /b8bac9100447414fae248cf58e81d90a~tplv-k3u1fbpfcp-watermark.image?)]

2. Mobile phone number decryption method

Use the click event of the button component open-type="getPhoneNumber" @getPhoneNumber = getPhoneNumber to obtain the encrypted mobile phone number. It is recommended to use the back-end decryption to obtain the code returned by uni.login and then pass it to the back-end to complete the login and obtain the mobile phone Registration and other information address

insert image description here

package request

You can use the uview packaged method, or you can package it yourself

Multiple data request loading processing

Initiate multiple data requests at the same time to determine whether the last request is over. If the last request is over && this request is over, close loading.
Refer to other loading encapsulation ideas

`// const baseUrl = xxxx;
var num = 0;
export default function requset(url, data = {}, method = "GET", getToken = true,isShowLoading = true, ) {
if (isShowLoading) {
	num++;
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
}
let token = uni.getStorageSync('token')
const header = {
	'content-type': 'application/json',
}
if (getToken) {
	header.Authorization = token
}
return new Promise((resolve, reject) => {
	uni.request({
		url: baseUrl + url,
		data,
		method,
		timeout: 10000,
		header,
		success(res) {
			resolve(res)
		},
		fail(err) {
			if (err.errMsg == 'request:fail timeout') {
				uni.showToast({
					title: '请求超时,请重试!',
					duration: 2000,
					icon: "none"
				});
			} else if (err.errMsg == 'request:fail ') {
				uni.showToast({
					title: '无网络!',
					duration: 2000,
					icon: "none"
				});
			} else {
				uni.showToast({
					title: '服务器错误',
					duration: 2000,
					icon: "none"
				});
			}
			reject(err)
		},
		complete() {
			if (isShowLoading) {
				setTimeout(() => {
					num--;
					console.log('第几次', num)
					if (num === 0) {
						uni.hideLoading()
					}
				}, 200)
			}
		}

	})
})
}
//在api.js中引入次方法 并且暴露出去
import requset from './requset.js'
export function getLoginUserInfo() {
    return requset('/wx/mini/getLoginUserInfo')
}
The second encapsulation method using uview

The official uni has no route interception, and the route interception of uview is used here

const request = (Vue) => {
	Vue.prototype.$u.http.setConfig((config) => {
		config = configs
		return config
	});
	// 请求拦截
	Vue.prototype.$u.http.interceptors.request.use((config) => { 
		uni.showLoading({
			title: '加载中',
			mask: true,
		});
                //设置token
		config.header.Authorization = uni.getStorageSync('Authorization') || '';
		return config
	})

	// 响应拦截
	Vue.prototype.$u.http.interceptors.response.use((response) => {
		if (response.data.status != 200) {
			uni.hideLoading();
			uni.showToast({
				title: response.data.msg,
				icon: 'none',
				duration: 2000
			})

		}
		return response;
	}, (err) => {
		uni.hideLoading();
		// 对响应错误做点什么 
		if (err.errMsg == 'request:fail timeout') {
			uni.showToast({
				title: '请求超时,请重试!',
				duration: 2000,
				icon: "none"
			});
		} else if (err.errMsg == 'request:fail ') {
			uni.showToast({
				title: '无网络!',
				duration: 2000,
				icon: "none"
			});
		} else {
			uni.showToast({
				title: '服务器错误',
				duration: 2000,
				icon: "none"
			});
		}
		return err
	})
}
export default request;

Interface request (the uview packaged api used here is used directly)

const http = uni.$u.http;
const api = '/api';
//get请求
export const getUserInfo = (params) => http.get(api + '/xxx', {params})
//post 请求
export const login = (data) => http.post('/xxx', data)

get address

Use uni.getLocation() to obtain the latitude and longitude. Before again, you need to determine whether the user is authorized. If not authorized, cooperate with uni.openSeting() to guide the user to authorize. Use uni.authorize() to determine whether the user is authorized. If you are not authorized, call uni.openSeting, and if you are
authorized, call uni.openSetting uni. getLocation

    	uni.authorize({
		scope: 'scope.userLocation',
		success(res) {
		uni.getLocation({
                       type: 'gcj02 ',
                       success(res) {
                       const latitude = res.latitude;
                       const longitude = res.longitude;
			}
		)},
		fail(err) {
                    uni.showModal({
                    title: '是否开启',
                    content: '当前需要获取您的地理位置',
                    showCancel:false,
                    success: function(res) {
                    if (res.confirm) {
			uni.openSetting({
			success(res) {											if (res.authSetting['scope.userLocation']) {
                                //执行你需要的请求操作
				} else {
					uni.showToast({
						title: '无法获取最近电站信息',
                                                duration: 2000,
						icon: "none"
					})}}
									})
								}
							}
						});
					}
				})
    

payment procedure

Use WeChat applet to pay uni.requestPayment() official website address

Usually the data required for WeChat payment is returned by the backend, you only need to call this api

// 仅作为示例,非真实参数信息。 uni.requestPayment({
    provider: 'wxpay',//微信付款
    appid:'',
    timeStamp: String(Date.now()), //时间戳
    nonceStr: 'A1B2C3D4E5', //随机字符串
    package: 'prepay_id=wx20180101abcdefg',//统一下单接口返回的 prepay_id 参数值
    signType: 'MD5',//加密方式
    paySign: '',//寄吗数据
    success: function (res) { console.log('success:' + JSON.stringify(res)); },
    fail: function (err) { console.log('fail:' + JSON.stringify(err)); } });

release

hubilder Click to publish to WeChat applet

If prompted after packaging

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Fdmrv5pa-1660528771035)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /adbae2a008d041f2aa8eca8e0dfd28cc~tplv-k3u1fbpfcp-watermark.image?)]

Open the source code view in mainfest.json and configure as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-sMcaZN2z-1660528771035)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /aa7b7f31b5764547bef684b3454716bb~tplv-k3u1fbpfcp-watermark.image?)]

Subcontract

  • The size of a single subpackage is 2m, and the WeChat applet stipulates that it cannot exceed 20m

  • To use WeChat applet subcontracting in uniapp, you need to enable subcontracting in manifest.json. The official website address is shown in the figure below

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-3bsYd54m-1660528771035)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /0d35cc98a71544e4a7907ca2a67eff2d~tplv-k3u1fbpfcp-watermark.image?)]

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-MZYdiKKj-1660528771036)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /03ccca0065ef42449f9af59be0ae0347~tplv-k3u1fbpfcp-watermark.image?)]

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-QeO1frZQ-1660528771036)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /f5e745cb0a45457193124a81371d8bc1~tplv-k3u1fbpfcp-watermark.image?)]

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-ItdOeJP1-1660528771036)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /4ec0d8fc6b844926b96e11ca989898af~tplv-k3u1fbpfcp-watermark.image?)]

At this point, the configuration has been completed, run to the WeChat developer tool, click on the details, and it has been displayed that we have added subcontracts.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-oD0QXRsi-1660528771037)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /fa8fb7e922bc4395be29bf9fd89836aa~tplv-k3u1fbpfcp-watermark.image?)]

news subscription

At present, news subscriptions are commonly used for one-time subscription and long-term subscription: long-term subscription is mainly developed for public units, so we use one-time subscription this time

WeChat official link

uniapp official link

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-nG6DbAab-1660528771037)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /d3da72aeb52e4edfb979841d6e3c413e~tplv-k3u1fbpfcp-watermark.image?)]

Before subscribing to news, we must set the message template in the background of the applet. Click to jump to the WeChat public platform to log in and set the message template in the subscription message column.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-yPk1K1lv-1660528771037)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /44519f8ff743416fb811180ab2e09c46~tplv-k3u1fbpfcp-watermark.image?)]

There are many kinds of official message templates, which can be matched by yourself. You can also apply for message templates

Here's how to use subscription messages in your project

   		uni.requestSubscribeMessage({
			tmplIds: ['HAAIddwfUie7huMk2D3QZ-xxxxxxxxxxxxx',
				'2zDrf9SNpGq6hU1vSbfLQganFnQE_xxxxxxxxxxxxx'
			],
			success(res) {
				console.log(res);
				// 值包括'accept'、'reject'、'ban'。
				// 'accept'表示用户同意订阅该条id对应的模板消息,
				// 'reject'表示用户拒绝订阅该条id对应的模板消息,
				// 'ban'表示已被后台封禁
				// if (res.errMsg == 'requestSubscribeMessage:ok') {
				// 	console.log('订阅成功');
				// 	uni.showToast({
				// 		title: '订阅成功'
				// 	})
				// }
			},
		})

Print event picture

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-YGNxDS4p-1660528771038)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /cf0ac3524db44fe68dc4bd468187444a~tplv-k3u1fbpfcp-watermark.image?)]

insert image description here

1. Just call the api after clicking the event. tmplIds is the message subscription template id, which can be multiple, but a maximum of 3 messages can be subscribed in one call;

2. TEMPLATE_ID is a dynamic template id, each message exists independently, if necessary, a single judgment is required;

3. If you check Always keep the above options, there will be no more pop-up prompts; if only one is checked, and you select Do not ask, there will be pop-up prompts;

4. If the cancel button is selected, it will always be in the rejection state by default and will not pop up a prompt. At this time, you need to guide the user to open the message prompt in uni.getSetting; withSubscriptions: Whether to obtain the subscription status of the user's subscription message at the same time, not obtained by default

(Tips: After opening the message notification in the real device test, click the subscribe message again and there will be no pop-up window; the correct way: clear the cache in the developer tool and recompile it into the real device, then click the subscribe message again to evoke the pop-up window normally event)

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-hZOVcl6p-1660528771039)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /6f36dd5fc05a4479b6ad50caa7042bbe~tplv-k3u1fbpfcp-watermark.image?)]

At this point, we have already completed half of the work, and later we need to push messages. Message push address

Message push can be server-side push or cloud function push

Message push is generally done by the backend. We can pass the parameters of the frontend to the server through the interface, and the server will push it to the user at an appropriate opportunity; note that the
data value should correspond to the key value of the message template;
insert image description here

(https://img-blog.csdnimg.cn/e755fe456a524e7eb4ae30ee3caa439e.png)

h5 adaptation problem

Regarding the h5 adaptation problem, I believe that many people have solutions. Share with me the solution. If you have a better method, please suggest it.

rem

rem i haven't used it

vw

  • vw : Relative to the width of the viewport, 1vw is equal to 1% of the viewport width (the total viewport width is 100vw)
  • vh : Relative to the height of the viewport, 1vh is equal to 1% of the viewport height (the total viewport height is 100vh)
  • vmin : Select the smallest of vw and vh
  • vmax : Select the largest of vw and vh

h5 adaptation solution

The solution provided by uniapp official website is to convert rpx to px.
Since rpx can be converted to px, we can also use px to vw

vw

  • Install the third-party plug-in postcss-px-to-viewport The projects created by normal uniapp have been installed

  • Create a postcss.config.js file in the project

  • Write something in the file

    viewportWidth: 375, // 视窗的宽度,对应的是我们设计稿的宽度,iPhone 6s 一般是37
    viewportHeight: 667, // 视窗的高度,iPhone 6s 一般是667
    unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数(很多时候无法整除)
    viewportUnit: "vw", // 指定需要转换成的视窗单位,建议使用vw
    selectorBlackList: [".ignore", ".hairlines"], // 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名
    minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值
    mediaQuery: false, // 允许在媒体查询中转换`px`
    fontViewportUnit: "vw", //字体使用的视口单位
    exclude: [/node_modules/], 
    

Since then, the commonly used functions have been basically completed, and the others are business logic. I will continue to share the problems encountered in the project later. Welcome everyone to pay attention to me

Guess you like

Origin blog.csdn.net/weixin_48164217/article/details/122582611