The first month in the new company, given a small program task, a front-end company is really said to be free and free, good and bad. The good thing is that I felt uncomfortable reading native applets, so I researched a wave of writing in Vue, so I found uni-app. When I started writing, the official advice was to use HbuildeX, so I used it for a while.

I. Preparation before development

  • Vue scaffolding
  • Wechat developer tools

Put the top stuff on yourself. La la la la

Developed in vscode

Let’s install a plug-in

Because of the use of applets, it is recommended to install a vscode plug-in for applets development assistant

The first plugin, ENMM, ignored (I’m here to write code, not to fish)

Of course, you also need to install vue syntax check plugin Vetur (you must have installed, want to write small programs in Vue).

To start developing

Let’s take a look at what it looks like (forget about aesthetics, after all, there’s no dedicated UI, I’m a front-end dude with no aesthetics)

I. Create a project

Open your favorite Powershell and write

Vue create -p dCloudio /uni-preset-vue mygreatePro // Follow is whatever your name isCopy the code

Select template, default template, press Enter, if you like TS, you choose TS.

And so on and so on and see

Don’t listen to him, we need to write a small program, should go into the project folder and execute

NPM run dev:mp-weixin // Development phase NPM run build:mp-weixin // Release phaseCopy the code

Two, get to work

1. Use vscode to open the project folder you created

In addition to those files, other projects with scaffolding to create look the same, more familiar, comfortable (I just hate wechat small program native framework why)

2. Preview in the Developer tools

After executing NPM run dev:mp-weixin, we can directly open the developer tool and import the project

I’m not going to write appID, but I’m not going to write it here, so I’ll just introduce it

If you have already applied, please use your vscode, open the manifest.json file, and find this place

	"mp-weixin": { /* wechat applets are unique */
		"appid": "Appid here."."setting": {
			"urlCheck": false
		},
		"usingComponents": true
	}
Copy the code

Then go to preview and see something like this:

Just like the

3. Start development

Let’s look at what’s already online

I hit people if I think they’re ugly

1. Analyze requirements

Three TAB pages, obviously login authorization, plus a login page.

Okay, let’s get the page ready

Don’t forget to also write pages. Json, so that wechat can handle (wechat said)

The tabBar in pages. Json also needs to be configured because it is a TAB TAB

 "tabBar": {
    "color": "#8a8a8a"."selectedColor": "#d4237a"."backgroundColor": "#fff"."position": "bottom"."borderStyle": "black"."list": [{"pagePath": "pages/anchor/index"."text": "The host"."iconPath": "static/tabar/1-1.png"."selectedIconPath": "static/tabar/1.png"
      },
      {
        "pagePath": "pages/withdraw/index"."text": "Withdrawal"."iconPath": "static/tabar/2-1.png"."selectedIconPath": "static/tabar/2.png"
      },
      {
        "pagePath": "pages/mine/index"."text": "I"."iconPath": "static/tabar/4-1.png"."selectedIconPath": "static/tabar/4.png"}}]Copy the code

You can see that the corresponding static image files are placed under static, but please note that CSS style files should not be placed under static, otherwise they will not compile to WXSS, and you will have a long time to worry about

That’s it, that’s it, you can see it in the developer tools

That’s done.

2. The button

I use SCSS, so I need yarn add sass-loader node-sass

Dlould provides the uni-UI framework, which is rich in components, so use it

1. Steps to use UNI-UI
  • Install yarn add@dcloudio /uni-ui
  • Use local import, register, use

It is recommended to read it directly on NPM www.npmjs.com/package/@dc…

2. Use a wave on my anchor page

A TAB – like component called a splitter

  • 1. Copy the step code on NPM

    • import {uniBadge} from '@dcloudio/uni-ui'
      export default {
          components: {uniBadge}
      }
      Copy the code
  • 2. Find the corresponding component name to replace with uniSegmentedControl

  • 3. To find HTML structures, you can search the plugin market for the name of every plugin you need without the uni prefix

  • 4. After you find it, use the template file according to the document

    Plugin address: ext.dcloud.net.cn/plugin?id=5…

Note: Here comes the pit, sample code in the documentation for handling click events that switch between different views

I’m going to use e, and I’m going to use index, so I’m going to change index to e

Tips: If you find that the applet preview hasn’t changed, you can recompile it, which is occasionally necessary to introduce new components

And now preview discovery

Have it!

Next up:

I. Login authorization

1. Login mechanism of applets

  • Traditional login (JWT as an example)

    • The user enters the user name and password (the password must be encrypted by some algorithms) to access the login interface

    • The back-end verifies the user name and password, encrypts the user information into a token string, and returns it to the front-end

    • Localization are the front-end token preserved (storage, here involved in a job interview: the localstorage, sessionstorage, what is the difference between a cookie? Ask yourself.)

    • Every time the front-end sends a request, it sends the token to the back-end, and the back-end determines whether the login status is legitimate (how to transmit the token, whether to put it in the head or the body).

    • And then the front end decides what to do based on what comes back, right

      What is the difference between cookie, session and token? Recommend an article, can take a look, do not understand the small partner juejin.cn/post/684490…

  • Applets login authorization applets have no login box, but only one authorization user information, so what is the processing process? Simple steps are: get user information to do authorization —–> call wx.login interface ——> get the returned unique authentication code—–> connect the code with user information to your backend —–> the same as above

One thing to note

  • Code can only be used once and will expire in five minutes. Wx.login ()

2. We do login authorization

2-1. Think about the scenario

Before loading the small program, check whether you have logged in. If not, jump to the login interface (or directly call the interface to obtain user information and login interface).Copy the code

2-2 Judgment before landing

Before loading the small program, determine whether to log in, and do the corresponding jump

How to judge before loading? ——> Lifecycle hook functions

When we open app. vue in our project, we see the following code:

        onLaunch: function() {
            // The app initialization is complete
            // Note that the global trigger only happens once!!
			console.log('App Launch')},onShow: function() {
            // The app starts from the background
            // This is obviously a good chance to check if you have logged in
			console.log('App Show')},onHide: function() {
            // App goes from foreground to background
			console.log('App Hide')}Copy the code

So the way to judge

 onShow: function() {
    // Check which permissions have been obtained
    wx.getSetting({
      success(res) {
        // Check if there is any user information, if not, then you are not logged in
        if(! res.authSetting["scope.userInfo"]) {
            // Close all pages and go to the in-app login page
          wx.reLaunch({
            url: "/pages/authorise/index"}); }}}); },Copy the code
Small procedures between page jump related API
wx.reLaunch(); // Close all pages to open a page within the app
wx.switchTab(); // Jump to the tabBar page and close all other non-Tabbar pages
wx.navigateTo(); // Jump to a page
wx.navigateBack(); // Return to previous page with navigateTo
Copy the code

Please refer to the WX documentation for specific usage. If you can’t see it, please refer to the UNIapp documentation. It looks the same anyway

Uniapp API package inherits applets API, basically applets API in front of the word wx change to uni can be used

2-3. Login operations

Some of wechat’s permission apis have been deprecated, and now only some permission operations can be performed through button’s Opentype attribute. The following code includes handling the second boot authorization login process after the user rejects authorization

<button open-type="getUserInfo" lang="zh_CN"  @getuserinfo="mpGetUserInfo" size="mini" v-if="show">Authorized to log in</button>
<button type="primary" size="mini" open-type="openSetting" @opensetting="reauthorize" v-else>reauthorization</button>
Copy the code
 // After obtaining the user information, call the login interface, if the authorization is rejected, jump to the setting page
    mpGetUserInfo(result) {
      const that = this;
      // Check whether authorization is granted
      wx.getSetting({
        success(res) {
          if (res.authSetting["scope.userInfo"]) {
            // The avatar nickname can be obtained by calling getUserInfo
            wx.getUserInfo({
              success: function(res) {
                that.userInfo = res.userInfo;
                wx.login({
                  success: function(loginRes) {
                    that.userInfo.code = loginRes.code;
                    that.$http({
                        url: "Login interface address".data: that.userInfo,
                        method: "POST"
                      })
                      .then(res= > {
                        // The login fails. An error message is displayed and the authorization page is opened again
                        ifWx. redirectTo({wx. RedirectTo ({wx.url: ""
                          });
                          // Successful login
                        } else {
                          // Save the token obtained after login
                          wx.setStorageSync("token", res.data.userinfo.token);
                          // Save the returned processed user information
                          uni.setStorageSync("login", res.data.userinfo);
                          // The login succeeds and the TAB page is displayed
                          wx.switchTab({
                            url: ""}); }}); }}); }}); }else {
            that.show = false; }}}); },// Handle the reauthorization callback function
    reauthorize(e) {
      if (e.detail.authSetting["scope.userInfo"]) {
        // If the second authorization succeeds, switch the display button in the dialog box
        this.show = true; }}Copy the code

This.$HTTP = “HTTP”; this.$HTTP = “HTTP”;

Continue to see a joke first, three days, little brother has not received the salary, very annoying oh, let’s touch fish, friends

In the last book

This.$HTTP sends a request. What is this?

1. Send requests in VUE project on PC

Dumb step :(using axios)

Yarn add axios // NPM also worksCopy the code
// In the CLI project
/ / the main js
import axios from 'axios'
// Configure the request root path
// If the baseURL is configured with a cross-domain proxy, give it the name assigned to the proxy
axios.defaults.baseURL = '/api'
// Configure request interceptor
axios.interceptors.request.use(config= > {
 // Do all kinds of preprocessing, add token, block permission access whatever
  return config
}, (error) = > { return Promise.reject(error) })

axios.interceptors.response.use(config= > {
  return config
})

// Mount to vue
Vue.prototype.$http = axios
Copy the code

Two, small program request

1, the original approach:

wx.request({
  url: 'test.php'.// This is an example, not a real interface address
  data: {
    x: ' '.y: ' '
  },
  header: {
    'content-type': 'application/json' / / the default value
  },
  success (res) {
    console.log(res.data)
  }
})
Copy the code

Xue is a little sad, because used to axios, support promise, then we let her support promise

2. Encapsulate a small request function that supports Promise

  • Create a new request.js file and put it in a folder called utils (I won’t tell you what utils means)
  • Export a default function object
  • The resolve () function returns a promise, a resolve () and a reject () promise
export default() = > {return new Promise((resolve,reject) = >{})}Copy the code
  • 4, encapsulate wechat API (UNIAPP API is also ok, if there is cross-end demand, directly encapsulate UNI requestAPI, almost long)
export default() = > {return new Promise((resolve,reject) = >{
        wx.request({
        url: 'test.php'.// This is an example, not a real interface address
        data: {
            x: ' '.y: ' '
        },
    header: {
        'content-type': 'application/json' / / the default value
    },
    success (res) {
        console.log(res.data)
        }
    })
    })
}
Copy the code
  • 5, continue to package, can not be directly used now
// Pull out variable parameters, such as URL, methods, and data, and pass them as parameters to remove the result of a request's success or failure
export default (params) => {
    return new Promise((resolve,reject) = >{ wx.request({ ... paramsheader: {
                'content-type': 'application/json' / / the default value
            },
            success (res) {
               resolve(res)   // Resolve will return res or res.data
            }
            fail: (err) = > {
              reject(err)
            },
        )
    })
}
Copy the code
  • Axios has a baseURL to save effort, so should we
export default (params) => {
    const baseUrl = "Write the public part of your own address."
    return new Promise((resolve, reject) = >{ wx.request({ ... params,url: baseUrl + params.url,
            success: (res) = > {
                resolve(res.data)
            },
            fail: (err) = >{ reject(err) } }); })}Copy the code
  • 7. Process the request header
// For example, you need to carry token requests
// For example, if you need to set some field types, do it here
export default (params) => {
    const baseUrl = "https://www.jianbingkonggu.com/"
    let head = {}
    if{head["token"] = uni.getStorageSync('token');
    }
    head['Content-Type'] = 'application/x-www-form-urlencoded'
    return new Promise((resolve, reject) = >{ wx.request({ ... params,url: baseUrl + params.url,
            header: head,
            success: (res) = > {
                resolve(res.data)
            },
            fail: (err) = >{ reject(err) } }); })}Copy the code
The full version
export default (params) => {
    const baseUrl = "https://www.jianbingkonggu.com/"
    let head = {}
    if(! params.url.includes("/MiniProgramLogin")) {
        head["token"] = uni.getStorageSync('token');
    }
    head['Content-Type'] = 'application/x-www-form-urlencoded'
    return new Promise((resolve, reject) = > {
        // To make the user more comfortable
        // create a loading animation
        uni.showLoading({
            title: 'Loading'}) wx.request({ ... params,url: baseUrl + params.url,
            header: head,
            success: (res) = > {
                resolve(res.data)
            },
            fail: (err) = > {
                reject(err)
            },
            complete: () = > {
                // Request completed
                // Hide the loading dialog boxuni.hideLoading() } }); })}Copy the code

2. How to use it in the project?

In a word, same as Axios

  • The introduction of
  • mount
  • use

In the main. In js

import Request from './utils/request'
Vue.prototype.$http = Request
Copy the code

Then you can happily use this.$HTTP (various parameters).then() in a single vue component

What other skills do we need? Write applets with VUE

Do not doubt, Shandong people just like to inverted sentence zha as if there is nothing direct

NPM run dev:mp-weixin CTR +c = NPM run build:mp-weixinCopy the code

Close the project in the previous developer tool and reintroduce the MP-Weixin folder in the build folder under the Dist folder. This is the file we packed. After introducing it, test it by yourself and click the upload button in the upper right corner of developer tool to upload the code. Then log in the wechat applet background to submit the code for review.