Small program has been very popular today, as a member of the software system, more and more companies and individuals are developing their own small program, and small program is no longer a single wechat small program, there are Baidu small program, Alipay small program, douyin small program and so on. Small program is a very good development technology, is also easy to find a job skills, this article refers to let everyone quickly understand the micro channel small program and development.

The preparatory work

Before entering applets development, there are a few things to prepare for:

  1. Register an account on wechat public account platform
  2. Understand applets development documentation (easy reading)
  3. Download and install wechat Developer tools

When the above steps are ready, we officially enter the small program development, follow my steps to go down!

start

First open the developer tool, you will see the following interface, which needs to pay attention to two points:

  • Back-end services: Since this is an introductory experience, I chose not to use cloud services. I will introduce cloud development later.
  • Language: Typescript and JavaScript. For us backend developers, JavaScript

After successfully creating the project, the specific project structure is shown in the figure below

  • Pages: a place where project pages are stored
  • Utils: a utility class method written in JS
  • App. json: Global configuration of the applet, including title, color scheme, etc
  • App.js: Getting started with apps

To learn more, go to Configuration description

Try modifying the contents of navigationBarTitleText in app.json

File Type Introduction

wxml

The file with the WXML suffix is the HTML page in the applet. If we open page/index/index.wxml, the

tag is the familiar

tag.

For more information => Component documentation links

wxss

WXSS can be understood as CSS style files, WXSS has most of the features of CSS, small programs in WXSS also made some expansion and modification.

For example, we added dimension units. When writing CSS styles, developers need to take into account the screen widths and pixel differences of mobile devices and use some tricks to convert these pixels. WXSS supports a new dimension unit RPX in the bottom layer, so developers can save the trouble of conversion, as long as the laughing program to the bottom layer to convert, because conversion uses floating point number operation, so the calculation result will be a little deviation from the expected result

js

The core logic of the applet is in the JS file, the overall feeling of the applet development is like a mixture of Vue and React, that is, there is data definition and {{}} two-way binding and Wx :if tag, as well as setState syntax concepts, the applet unique life cycle function.

Practical knowledge

With the above description, let’s modify the contents of these files and write some of our own,

app.js

Here will print a log life cycle method, small program started!

app.json

The bottom TAB navigation bar is displayed

pages/index/index.wxml

So here we’ve changed the home page to what we want it to look like,

equals

index.js

Data defines data, onxxx is the page life cycle method, and the table identifies the different states of the page

Save the compilation and run it, and you’ll see the following

At this point, is equal to say that the completion of a simple small program page, how to do their own page, but this point is useless, interaction? Button? What about some dynamic effects? Nothing, next to expand the functionality, here will learn the API use of small programs

Event binding for applets

In the index. WXML file, the

Since the button references these 4 methods, we need to define these 4 function methods. As mentioned earlier, the logic of the page is all in the JS file, so in index.js, we append 4 methods, which are as follows

Page({
  toast() {
    wx.showToast({
      title: 'success',
      icon: 'success',
      duration: 2000
    })
  },
  toLog() {
    wx.switchTab({
      url: '/pages/logs/logs',}}),showLoading() {
    wx.showLoading({
      title: 'Loading',})setTimeout(function () {
      wx.hideLoading({
        complete: (res) => {
          console.log('Effects disappear while loading')},})}, 3000)},showModeal() {
    wx.showModal({
      title: 'Sure? ',
      content: 'This is a simulated popover.',
      cancelColor: 'red',
      success(res) {
        if (res.confirm) {
          console.log('User hits OK')}else if (res.cancel) {
          console.log('User hit Cancel')}}})},})Copy the code
  • Wx.showtoast () : a prompt box is displayed
  • Wx. switchTab() : Switches the contents of the bottom TAB
  • Wx.showloading () : displays the loading effect
  • Wx.hideloading () : Turns off the loading effect
  • Wx.showmodal () : Displays a prompt box with a select button

XXX (){} is a declaration of a method, special is the inside of it, wx.xxxxxx, this is the wechat API, just like the Java framework API method list.isempty (), the micro envelope is filled with wX. Want what kind of function directly. It is good to get out and use it. The meaning of parameters are defined by wechat

For more information => wechat apPLETS API guide

The display function is added

Go back to the previous index.wxml file and append the following

index.js

Append the following content to the page logic JS file

  handleInput(e){
    console.log('input',e.detail)
    React setState
    this.setData({
      # val is the defined attribute and e is the input event object
      val: e.detail.value
    })
  },
  add(){
    this.setData({
      The toDOS attribute value of the original data object is iterated over to a new toDOS object, and the data object val is appended to the new TODOS
      List newBooks = list.stream().map(b->Book).add(newBook).tolist ()
      todos: [...this.data.todos, this.data.val],
      val: ' '})},Copy the code

The end result looks like this

Extended experience

Use wechat’s camera API

index.wxml

Add the

TAB content to use the built-in camera

<view>
	<camera style="width:100%; height:300px;">
	</camera>
	Bind the takePhoto method to the button
	<button type="primary" bindtap="takePhoto"</button> </view>Copy the code

index.js

Add an implementation of the takePhto method

takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: res => {
        this.setData({
        # Change the SRC address of the image
          src: res.tempImagePath
        })
      }
    })
  },
Copy the code

Media player

index.wxml

Add

<view>
	<audio poster="{{poster}}" name="{{musicName}}" author="{{author}}" src="{{musicSrc}}" id="myAudio" controls loop></audio>
	<button type="primary" bindtap="audioPlay"</button> <buttontype="primary" bindtap="audioPause"</button> <buttontype="primary" bindtap="audio14"</button> <buttontype="primary" bindtap="audioStart"</button> </view>Copy the code

index.js

The following content is consistent with the operation guide of the official document

OnReady (e) {// Use wx.createAudioContext to get audio context this.audioctx = wx.createAudioContext('myAudio')},audioPlay() {
    console.log(this.audioCtx)
    this.audioCtx.play()
},
audioPause() {
    this.audioCtx.pause()
},
audio14() {
    this.audioCtx.seek(14)
},
audioStart() {
    this.audioCtx.seek(0)
},

Set the property content for data, since the 
      
data:{
    musicName: 'People like me',
    author: 'Hair is not easy',
    poster: 'http://singerimg.kugou.com/uploadpic/softhead/400/20180611/20180611160019456.jpg',
    musicSrc: 'https://sharefs.yun.kugou.com//202004130106//5f99b0098214a54497e4e59d041d0064//G146//M07//02//14//cpQEAFwqEt2AMf4dACiMs ITsnwk265.mp3',}Copy the code

The song is playing! ~

Get the user’s information

index.wxml

Use the

<view class="userinfo">
   ## wx:if displays this button if there is no user information
	<button wx:if="{{! hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"</button># Display avatar and nickname if there is one
	<block wx:else>
		<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
		<text class="userinfo-nickname">{{userInfo.nickName}}</text>
	</block>
</view>
Copy the code

index.js

Define several attributes for the data object
data:{
 userInfo: {},
 hasUserInfo: false,
 canIUse: wx.canIUse('button.open-type.getUserInfo')}# add method
bindViewTap: function () {
    console.log('Someone clicked on their profile picture.')
},
getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
          userInfo: e.detail.userInfo,
          hasUserInfo: true})},Copy the code

Explanation of userInfoReadyCallback in wechat Demo

Database operations for cloud development

Start by clicking the Cloud Development button in the development toolbar, which will lead you to start cloud development

Add the following code to index.js. For more information, see the cloud Development Guide

 onLoad() {
    console.log('Index page load pull')
    this.getbooks()
  },
  getbooks() {
    # wechat cloud development API use, fixed syntax, here to get all the data
    wx.cloud.database().collection('bookdb').get({
      success(res) {
        console.log('Get book data', res)
        this.setData({
          books: res.data
        })
      }
    })
  },
Copy the code

The effect is shown below, loading the data that was previously inserted into the database

The source address

All project code for this article

Pay attention and don’t get lost

The article continues to update every week, you can wechat search “ten minutes to learn programming” the first time to read and urge more, if this article is written well, feel something ~ for praise 👍 for attention ❤️ for share ❤️ everyone’s support and recognition, is the biggest power of my creation, we see the next article!