1. First acquaintance with wechat applets
1) Why applets exist?
2) Provide convenient user connection tools for enterprises or alumni; It can replace part of the function of mobile phone APP to a certain extent.
3) Product design standards: small but beautiful, short development cycle.
4) cloud development for developers to provide complete primary support and the clouds WeChat service support, and weaken the back-end and operational concepts, do not need to set up the server, use the API provided by the platform in terms of core business development, can be realized fast on-line and iteration, this ability at the same time, with the developers are already using cloud services compatible with each other, are not mutually exclusive. Tencent cloud development technology, free resource quota, no domain name and server can be set up
5) Small programs can be opened in wechat without downloading APP or visiting traditional PC sites, and can interact anytime and anywhere
2. Preparation before the development of wechat small program
- Read official documents of wechat applets:
Developers.weixin.qq.com/miniprogram…
- Download and install “wechat User Development Tool” :
Developers.weixin.qq.com/miniprogram…
3) Register an alumni mini program account (MP of alumni Association management background)
Developers.weixin.qq.com/miniprogram…
3, small program management background basic operations
(I) Version management
Mini program certification: fill in the basic information, pay attention to the choice of industry categories, record fee of 300 yuan.
There are three versions of applets: development version, review version and online version (the default code size cannot exceed 2M).
Static resources used in small program projects can be put on CDN or Tencent cloud to reduce the code volume.
(ii) Member management
The administrator (1 person) is a wechat user who registered the account.
Project members (15), can log in the small program management background, developers must be project members.
Experience members (15 people), only experience authority, no development authority.
(3) Development management
AppID, which is the id number of a small program, is used to create projects, debug projects, jump between small programs, and things like payments.
AppSecret, small program key, generally to the back end, in login, payment and other functions are used.
Request address, is the API baseURL, local development can turn off HTTPS authentication, online must be small program management background add this address, and require HTTPS protocol.
4. Basic use of wechat developer tools
1) How to create a new project?
Developers.weixin.qq.com/miniprogram…
2) Debugging projects (real machine debugging, wechat developer tool debugging)
Developers.weixin.qq.com/miniprogram…
3) Pay attention to the compatibility between the apPLETS API version library and wechat version.
5. Know the four kinds of documents
.wxml, an HTML-like role
.wXSS, with most of the features of CSS, small procedures in WXSS also made some expansion and modification.
.js, write scripts to interact with the user, respond to the user’s click, get the user’s location and so on.
Json is a data format, not a programming language. Json plays the role of static configuration in applets.
6, own configuration style small procedures
The app.json file in the root directory of wechat applets is used for global configuration of wechat applets, determining the path of page files, window performance, setting network timeout, setting multiple tabs, etc.
{ "pages": [ "pages/index/index", "pages/books/books" ], "window": { "backgroundTextStyle": "Light", "navigationBarBackgroundColor" : "# FFF", "navigationBarTitleText" : "alumni association small program", "navigationBarTextStyle" : "black" }, "tabBar": { "color": "#aaaaaa", "selectedColor": "#ff0000", "list": [ { "pagePath": "Pages/index/alumni", "text", "looking for alumni," "iconPath" : "/ assets/tabbar/alumni. PNG", "selectedIconPath" : "/assets/tabbar/alumni-on.png"}, {"pagePath": "pages/reg/reg", "text": "alumni registration ", "iconPath": "/assets/tabbar/reg.png", "selectedIconPath": "/assets/tabbar/reg-on.png" } ] } }Copy the code
7. App class and app-level lifecycle
Enroll alumni applet. Accepts an Object parameter that specifies the life cycle callback of the applet, etc.
App() must be called in app.js, and must be called only once. Or there will be unintended consequences.
App({// entire alumni applet onLaunch() {wx.login({success: res => console.log(' alumni login ', res.code)})}, globalData: { userInfo: null, } })Copy the code
Page class and page-level lifecycle
Page({
data: { },
onLoad: function (options) { },
onReady: function () {},
onShow: function () { },
onHide: function () {},
onUnload: function () {},
onPullDownRefresh: function () { },
onReachBottom: function () { },
onShareAppMessage: function () { }
})
Copy the code
Component Class and Component level lifecycle
Component({properties: {}, // data: {}, // own state data: {}, // life cycle methods: {} // own method})Copy the code
10. Customize alumni Card** Card** components
# card.wxml {{item.card_zh}} # card.wxss .card_item { padding: 0 10rpx; display: inline-block; border: 1rpx solid #ccc; line-height: 45rpx; } .card_item.on { color: red; } # card.js Component({ properties: { list: {type: Array, value: [] }, value: {type:String, value: ''} }, methods: {tapClick(e) {// parent component event communication // this.triggerEvent('input', E.target.dataset. Cate) // model bidirection.setData ({value: E.target.dataset. Cate})}, // LifeTimes: {}, pageLifetimes: {}}) # card.json {" Component ": true}Copy the code
11, use custom packaged **Card** components
# alumni.json
{
"usingComponents": {
"qf-cate": "/components/card/card"
}
}
Copy the code
12. List Rendering (Alumni List)
<block
wx:for="{{alumniList}}"
wx:for-item="alumni"
wx:key="alumni"
wx:for-index="idx"
>
<view class="row">
<text>{{idx+1}}</text>
<text>{{alumni.id*100}}</text>
<text>{{alumni.name}}</text>
</view>
</block>
Copy the code
13. Conditional Rendering (Alumni Homepage)
< view wx: if = '{{independence idx = = = 1}} "> alumni name < / view > < view wx: elif =' {{independence idx = = = 2}}" > college alumni class < / view > < the view Wx: elif = '{{independence idx = = = 3}} "> < / view > alumni work < view wx: else > alumni industries < / view > < button bindtap =' toggle '> switch < / button > <! , similar to show and hide, v - show - > < view hidden = "{{'}}" > < / view > more alumni informationCopy the code
Dynamic styles
<view class="box {{bol?'box':'box2'}}"></view>
<view style='color:red;font-size:{{size+"rpx"}}'>动态样式文字</view>
Copy the code
15. Event bind/catch
<! <view data- MSG ='hello bind' bindtap='click1'> </view> < catchtap='click2'> </view> </view> Page({data: {{}, click1 (e). The console log (" click1 ", e) console. The log (' alumni CARDS, e. arget. Dataset. The MSG)}, click2 (e) {the console. The log (' click2 ', e) }, clickOuter(e) { console.log('outer', e) } })Copy the code
16. Form binding (one-way binding, two-way binding)
<view> <input type="text" value='{{username}}' bindblur='usernameChange' /> <input type="text" Model :value='{{password}}' /> <button bindtap='submit' </button> </view> Page }, // Manually set the value usernameChange(e) {console.log('e', e.daile.value) this.setdata ({username: e.detail.value}) }, submit() { const data = { username: this.data.username, password: This.data.password} console.log(' Submit alumni registration ', data)}})Copy the code
17. Wechat mini-program animation (latest writing method)
<view class=" ABC "></view> <button bindtap='startAnim'> </button> Page({data: {}, startAnim() {// Create animation // The first argument is the node selector // the second argument is the dynamic frame (array) // the third argument is the filter time // the fourth argument is the callback argument, used to clear the animation, Animate ('.abc', [{opacity: 1.0, rotate: 0, backgroundColor: '#FF0000', scale: [1,1]}, {opacity: 0 0, rotate: 45, backgroundColor: '#00FF00', scale: [0.6,0.6]}, {opacity: 0.2, rotate: 80, backgroundColor: '#FF0000',scale: },], 5000, ()=> {// Clear the animation // its second parameter, which controls whether the style of the animation retains the style of the last frame. The default is this.clearAnimation('.abc', {opacity: Rotate: false, // backgroundColor: false}, ()=> {console.log(" Clean animation successfully ")})})Copy the code
18. Use Canvas Canvas (latest version)
<canvas type="2d" class=" AD "id="myCanvas"/> <button bindtap='save'> Save to alumni album </button> Page({data: { }, rpx2px(arg) { const res = wx.getSystemInfoSync() return res.screenWidth * arg / 750 }, Async getImage(path) {const c = wx.createOffscreencanvas ({type: const c = wx.createOffscreencanvas ({type: const c = wx.createOffscreencanvas ({type: const c = wx.createOffscreencanvas (); '2d'}) const image = c.createImage() await new Promise(resolve => { image.onload = resolve image.src = path }) return image }, onReady() { const $ = wx.createSelectorQuery() $.select('.ad') .fields({ node: true, size: }).exec((res) => {this.canvas = res[0]. Node const CTX = canvas. GetContext ('2d') FillStyle = 'orange' ctx.fillrect (0, 0, this.rpx2px(750), this.rpx2px(500)) // step 2, Font = "bold 25px serif" ctx.fillstyle = 'white' ctx.filltext (' list of graduates ', this.rpx2px(0), This.rpx2px (50)) This.getimage ('/assets/alumni.png'). Then (img=>{ctx.drawimage (img,50,50)})})}, // Convert canvas canvas to temporary path wx.canvastotempFilepath ({x: 0, y: 0, width: this.rpx2px(750), height: this.rpx2px(500), destWidth: 1500, destHeight: 1000, canvas: This canvas, success (res) {/ / save the picture in the temporary directory path to photo album wx. SaveImageToPhotosAlbum ({filePath: res tempFilePath})}})}})Copy the code
Small program first start request user authorization geolocation
# app.js app ({onLaunch() {// Get user's location authorization wx.getSetting({success(res) {console.log(' current user's location authorization list ', Res.authsetting) // If user is not authorized to geolocation if (! Res.authsetting ['scope.userLocation']) {// Wx.authorize ({scope: authorize) {// Authorize ({scope: authorize) 'scope.userLocation', success (res) {console.log(' console.log: alumni clicked yes ', res)}, fail (err) {console.log(' console.log: alumni clicked yes ', res)}, fail (err) {console.log(' console.log: alumni clicked yes ', res) Alumni click the reject 'res)}}}}}}}) # app. Json {" pages ": []," permission ": {" scope. UserLocation" : {" desc ": "In order to give you better alumni service, we hope to use your geolocation"}}}Copy the code
Use geolocation
<button > <map class="map" longitude='{{latLng. Longitude}}' </button> <map class="map" longitude='{{latLng. </map> <button bindtap='navTo'> </button> Page({data: {latLng: {}}, getLngLat() { var that = this wx.getSetting({ success(res){ if(res.authSetting['scope.userLocation']) { // GetLocation ({success(res) {console.log(' alumni user location ', res) that. SetData ({latLng: Res})}})}else{// If alumni users have refused geolocation, we need to open the built-in Settings page of wechat, Wx.opensetting ({success(res) {console.log(' user manually select authorization ', res)}})}})}, navTo() { wx.openLocation({ latitude: this.data.latLng.latitude, longitude: this.data.latLng.longitude, name: Address: 'Shenzhen University Alumni Association'})}})Copy the code
21. OnShareAppMessage implements forwarding
<button open-type='share'> <view> </button> Page({data: {}, // Two ways to implement forwarding (capsule button, button.open-type='share') onShareAppMessage(e) {console.log(' forwarding the school card ', E) if(e.rom ==='menu') {return {title: 'pages ', path: 'pages/good/good', imageUrl: 'HTTPS :good.jpg'}}else if(e.rom ==='button') {return {title:' I am talking for my school... ', path: 'pages/ad/ad', imageUrl: 'https://ad.jpg' } } } })Copy the code
22, globalData globalData
App({globalData: {MSG: 'Hello! ' } }) const app = getApp() Page({ data: { msg: App.globaldata.msg}, updateMsg() {app.globaldata.msg = 'alumni' this.setData({MSG: app.globaldata.msg})}) {{MSG}} modify the MSGCopy the code
OnPageScroll listens for page scrolling
<! </button> App({// page scrolling onPageScroll(e) {console.log(' page scrolling ', BackToTop () {wx.pagescrollto ({scrollTop: 133, duration: 2000})}})Copy the code
24. Realize media query
<! < p style =" max-width: 100%; clear: both; min-width: 1em;Copy the code
25. Drag and drop
<movable-area class="area"> <movable-view direction='all' x='{{point.x}}' y='{{point.y}}' bindchange='areaChange'> <view class="area-text">text</view> </movable-view> </movable-area> Page({ data: { point: {x:0,y:0} }, areaChange(e) { this.setData({point: e.detail}) } })Copy the code
26. Extremely powerful form components
<! -- Button is a form, <button open-type='contact'> </button> <button open-type='getPhoneNumber' Bindgetphonenumber ='getMobile'> log in to the alumni platform </button> <button bindtap='getUser'> get alumni information </button> <button </button> <button open-type='openSetting'> </button> </button> Page({data: {}, getMobile(e) {// The personal version of the small program console.log(' alumni phone number ', e)}, // to obtain user information, will be a box request user authorization // is about to become obsolete, It is recommended to use wx.getUserProfile to obtain user information getUserInfo(e) {console.log(' Get alumni user information ', e)}, getUser() {wx.getUserProfile({desc: 'For updating alumni membership information ', success(e) {console.log(' latest alumni user information ', e) // After receiving the user information, the interface will be sent to the backend database // Save alumni users in the business database}})}})Copy the code
27. Use components to select provinces and cities
<view class="section"> <view class="section__title"> <picker mode="region" bindchange="bindRegionChange" Value ="{{region}}" custom-item="{{customItem}}" > <view class="picker"> {{region [0]}}, {{region [1]}}, {{region [2]}} < / view > < / picker > < view > Page ({data: {region: CustomItem: 'All ',}, bindRegionChange(e) {console.log('region alumni ', e) this.setData({region: e.detail.value}) } })Copy the code
28, component use again example
<view class="section"> <view class="section__title"> Select industry type </view> <picker mode="selector" bindchange="bindTradeChange" Value ="{{tradeIdx}}" range='{{tradeArr}}' range-key='trade_zh' > <view class="picker"> {{tradeArr[tradeIdx].trade_zh}} </view> </picker> </view> Page({ data: { tradeArr: [{id: 0, trade: 'all' trade_zh: 'all'}, {id: 1, trade: "car", trade_zh: "Internet"}, {id: 1, trade: "office", trade_zh: "mobile Internet"}]. tradeIdx: 0 }, bindTradeChange(e) { console.log('trade picker', e) this.setData({tradeIdx: parseInt(e.detail.value)}) } })Copy the code
29. Use audio components
<audio poster="http://xxx.png" name=" author=" http://xxxxx.mp4" SRC =" id="myAudio" controls loop> </audio> < button bindtap = 'startPlay > play < / button > Page ({startPlay () {const audioCtx = wx. CreateInnerAudioContext () console.log('ctx', audioCtx) audioCtx.play() } })Copy the code
30. Use camera components
<camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 300px;" </camera> <button bindtap='takeCamera' </button> <image SRC ='{{avatar}}'> {avatar:''}, takeCamera() { const ctx = wx.createCameraContext() ctx.takePhoto({ quality: 'high', success: (res) => { this.setData({ avatar: res.tempImagePath }) } }) } })Copy the code
Small program route jump
<button bindtap='skipToTabPage'> jump to TabPage </button> <button bindtap='skipToNotTabPage'> jump to non-tab Page </button> Page({// jump to TabPage, SkipToTabPage () {wx.switchTab({url: '/pages/listen/listen'})}, // go to a non-tab page, use navigateTo, can pass the parameter NavigateTo ({url: '/pages/user/user? id=123&name=abc' }) } })Copy the code
32. Customize ActionSheet
<button bindtap='selectMethod'> </button> Page({selectMethod() {wx.showactionsheet ({itemList: [' send poster ', 'invite alumni '], success (res) {console.log(' select invitation method: ', res.tapindex)}})}})Copy the code
Use applets function API
<button bindtap='testWXApi'> </button> Page({testWXApi() {wx.setNavigationBartitle ({title:'1234'})) wx.setBackgroundColor({ backgroundColor: '#ff0000' }) wx.hideTabBar() } })Copy the code
34. Select photos from your phone’s album
<button bindtap='selectAvatar'> </button> Page({selectAvatar() {// Wx.getSetting can be used to determine whether the current user has access to the camera and album wx.chooseImage({ count: 9, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], Success (res) {// tempFilePath can be used as a SRC property to display images const tempFilePaths = res.tempfilepaths console.log('tempFilePaths', tempFilePaths) } }) } })Copy the code
35. Wechat Mini program alumni dues payment (pseudocode)
<button bindtap='pay'> </button> Page({pay () {// 1. Bind the existing payment account // in the small program management background; 2. Use wx.request to send the order information to the business server. Wx.requestpayment () {wx.requestPayment()}}Copy the code
Small program to achieve copy and paste, call, scan code function
<view bindlongtap='copy'> </view> <button bindtap='call'> </button> </button bindtap='scan'> </button> Page({// copy copy() { wx.setClipboardData({ data: 'ALULMNI2022211323' }) }, call() { wx.makePhoneCall({ phoneNumber: '0755-12345698'})}, scan() {wx.scancode ({scanType: 'barCode', success(res){console.log(' scan result ', res)}})}})Copy the code
Pull down refresh and bottom loading
Page({// Load onReachBottom() {console.log(' Bottom, }, // pull down refresh onPullDownRefresh() {console.log(' pulling down refresh ') setTimeout(()=>{// When the pull interface is complete, Wx.stoppulldownrefresh ()}, 1000)},}) #. Json LocalConfiguration {"navigationStyle": "custom", "onReachBottomDistance": 100, "enablePullDownRefresh": true }Copy the code
38. Request encapsulation
const baseUrl = 'http://localhost:8888'
const version = '/api/v1'
module.exports = function(url,method,data) {
return new Promise(function(resolve, reject){
wx.request({
url: baseUrl+version+url,
data,
method,
header: {
Authorization: wx.getStorageSync('token')
},
success (res) {
// 成功后数据过滤
resolve(res.data.data)
},
fail(err) {
wx.showToast({title:'网络异常'})
reject(err)
}
})
})
}
Copy the code
Wechat small program alumni login process
# app.js const API = require('./utils/ API ') app ({onLaunch() {// wx.login({success: FetchLogin ({code: => {console.log(' login ', res.code) // Call wx.request with code for token API. Res.code}). Then (res=>{// console.log(' login token', res) wx.setStoragesync ('token', Res.token)})}})}}) # node.js + Koa const axios = require('.. /utils/axios') const jwt = require('.. // const userModel = require('.. /model/user') class UserController {// static async login(CTX) {// Console. log('post body', Ctx.request.body) let {code} = ctx.request.body console.log('code', code) Const res = await axios({url: '/ SNS /jscode2session', method: 'get', params: { appid: 'w2x2f8b3892386e5e2ccf', secret: '345bc1b923ae7423bbf28146e31ff372e', js_code: Const list = await usermodel.find ({openID: 'authorization_code'}}) const list = await usermodel.find ({openID: res.openid}) if(list.length > 0) { const token = jwt.createToken(res) ctx.body = { err: 0, msg: 'success', data: { token } } }else{ const ele = { openid: res.openid, } await userModel.insertMany([ele]) const token = jwt.createToken(res) ctx.body = { err: 0, msg: 'success', data: { token } } } } } module.exports = UserControllerCopy the code
Write at the end
Small program native +ColorUI+ cloud function + cloud development +Json database
No matter which framework you choose, the basic knowledge of micro channel small program, basic concepts or take time to learn (see official documents or micro channel small program full combat, architecture design && pit strategy), because a lot of problems, the use of native to solve the better, components are also.