Note source: Hook Education – big front end employment Training camp

Content: Notes, thoughts and experiences in the process of learning

Tip: project actual combat article resources can not be uploaded, only for reference

Try to develop small projects

Preview/real machine debugging

Preview: you can simulate opening the small program on the mobile phone to view the effect

Real machine debugging: after opening the small program on the mobile phone, it will automatically synchronize after modifying the code

Note: The preview will automatically upload the code, the maximum is 2M, greater than 2M will report an error

Data interface

Application interface

  • Back-end engineer – Express development
  • Mock -API – e.g. Rap2, etc
  • Third party interface – for example: Zephyr weather (used in this case)

And the wind weather

  1. Registered account
  2. Create an Application: Wind Weather Console => Application Management => Create an application
  3. Apply for a KEY: Click Add Data KEY after the application is created
    • Key is the credential to invoke the interface
  4. The development integration
    • The syntax of the request interface
    • An example of returned data

Specific API can refer to zephyr weatherDevelopment of the document

Debugging interface

The interface debugging tool is used for the interface debugging that needs to be used. Insomnia is used in the course, and ApiPost is used here for debugging. Domestic software with friendly language is used

Call interface

Small program call interface usewx.request()Cloud API

Tip: In global configuration, the first page path of Pages is the default loading path

wx.request({
  // Request an address
  url: 'https://devapi.qweather.com/v7/weather/3d'.// Request parameters
  data: {
    location: '101010100'.key: '75174c6785044e3d91b7e1bc457ae702'
  },
  / / request header
  header: {
    // Returns JSON by default
    'content-type': 'application/json' / / the default value
  },
  // The request succeeded
  success (res) {
    console.log(res.data)
  }
})
Copy the code

Error content:XXXX is not in the list of valid request domain names, data cannot be obtained without resolving

  • Solution:
    • Development stage: do not verify legitimate domain names
      • Wechat developer tools => Details => Local Settings => Do not verify legitimate domain names
    • Online phase: Bind the domain name of the requested interface
      • Applets management background => Development Settings => Server domain name => Add a legitimate domain name

Separate encapsulation request

// Interface address
const BASE_URL = "https://devapi.qweather.com/v7"
/ / the key application
const KEY = "687e517f06684448a9f4695721414a07"

/** * API request function * parameters: URL address, request method, request parameters */
const request = (url, method, data) = > {
  // Add my wind weather KEY to the request parameter
  data.key = '75174c6785044e3d91b7e1bc457ae702'
  // Return a Promise wrapped return data
  return new Promise((resovle, reject) = > {
    // Call the applets API to get data
    wx.request({
      // The url address, using the generic request address plus the interface unique address
      url: BASE_URL + url,
      // Request mode
      method,
      // Request parameters
      data,
      / / request header
      header: {
        // Json data is returned by default
        'content-type': 'application/json'
      },
      // Request success triggers the Promise request success method, passing the parameters
      success (res) {
        resovle(res.data)
      },
      // Request failure triggers the Promise request failure method, delivering an error
      fail (err) {
        reject(err)
      }
    })
  })
}

/ / export
module.exports = {
  // Get the weather for three days
  threeDays: (data) = > {
    // Call the method encapsulated above, passing in the request address, request method, and request parameters
    return request('/weather/3d'.'get', data)
  }
}
Copy the code

Page to introduce the API interface

// pages/qweather/qweather.js
// Get wind weather encapsulation interface
const HFAPI = require('.. /.. /utils/api')

Page({

  /** * initial data for the page */
  data: {
    // Current latitude and longitude
    location: ' '.// Three days of weather data
    threeDays: [1.2.3]},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // bind this for later calls
    const that = this
    // Applets get the current location API
    wx.getLocation({
      type: 'wgs84',
      success (res) {
        / / dimensions
        const latitude = res.latitude
        / / longitude
        const longitude = res.longitude
        // Modify data
        that.setData({
          // latitude and longitude stitching
          location: longitude + ', ' + latitude
        })
        // Get data for three days, save data to data after success
        HFAPI.threeDays({location: that.data.location}).then(res= > {
          if(res.code === '200') that.setData({threeDays: res.daily})
        })
      }
     })
     
  },

  /** * lifecycle function - listen for the page to complete the first rendering */
  onReady: function () {},/** * lifecycle function -- listens for page display */
  onShow: function () {},/** * life cycle function - listen for page hiding */
  onHide: function () {},/** * life cycle function - listen for page unload */
  onUnload: function () {},/** * page-related event handlers -- listen for user pull actions */
  onPullDownRefresh: function () {},/** * the handler for the pull-down event on the page */
  onReachBottom: function () {},/** * Users click on the upper right corner to share */
  onShareAppMessage: function () {}})Copy the code

Error: getLocation requires a permission field declared in app.json

Solution: Declare permission field in app.json. After adding the field, a prompt will pop up when obtaining the location. Click confirm authorization to obtain the real location

  • "permission": {
      "scope.userLocation": {
        "desc": "Trying to get location information"}}Copy the code

Program interface

Official component: the component officially provided by wechat mini program

Wechat team launched third-party components -WeUI

  • Download it from gitHub

  • Introduction:

    • After decompressing, finddist/style/The followingweui.wxssfile
    • Copy the file to the applet root directory
    • In the global style file –app.wxssCan be introduced into@import 'weui.wxss';
  • Use:

    • Open the dist directory after decompression through wechat developer tools, and the sample code is shown below
    • You can also view the results on the website

Maps and lists

  • Add a list using WeUI’s list component
  • Add a map using the map component provided by the applet
<! --pages/qweather/qweather.wxml-->
<view class="container">
  <! -- Top map, set latitude and longitude, mark, zoom scale -->
  <map name="" longitude='{{longitude}}' latitude='{{latitude}}' markers='{{markers}}' scale="14"
    style="width: 100%; height: 160px"></map>
  <! -->
  <view class="weui-panel weui-panel_access">
    <view class="weui-panel__hd">Combination list</view>
    <view class="weui-panel__bd">
      <a class="weui-media-box weui-media-box_appmsg">
        <view class="weui-media-box__hd">
          <image class="weui-media-box__thumb" src="" alt></image>
        </view>
        <view class="weui-media-box__bd">
          <h4 class="weui-media-box__title">A title</h4>
          <view class="weui-media-box__desc">Giant spherical bodies made up of various kinds of matter are called planets. Planets have shapes and orbits.</view>
        </view>
      </a>
      <a class="weui-media-box weui-media-box_appmsg">
        <view class="weui-media-box__hd">
          <image class="weui-media-box__thumb" src="" alt></image>
        </view>
        <view class="weui-media-box__bd">
          <h4 class="weui-media-box__title">Title 2</h4>
          <view class="weui-media-box__desc">Giant spherical bodies made up of various kinds of matter are called planets. Planets have shapes and orbits.</view>
        </view>
      </a>
    </view>
    <view class="weui-panel__ft">
      <a class="weui-cell weui-cell_active weui-cell_access weui-cell_link">
        <view class="weui-cell__bd">To view more</view>
        <text class="weui-cell__ft"></text>
      </a>
    </view>
  </view>
</view>
Copy the code
// pages/qweather/qweather.js
// Get wind weather encapsulation interface
const HFAPI = require('.. /.. /utils/api')

Page({

  /** * initial data for the page */
  data: {
    / / longitude
    longitude: ' './ / dimensions
    latitude: ' '.// Current latitude and longitude
    location: ' '.// Three days of weather data
    threeDays: [1.2.3].// Map markers
    markers: []},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // bind this for later calls
    const that = this
    // Applets get the current location API
    wx.getLocation({
      type: 'wgs84'.success(res) {
        / / dimensions
        const latitude = res.latitude
        / / longitude
        const longitude = res.longitude
        // Modify data
        that.setData({
          / / longitude
          longitude,
          / / dimensions
          latitude,
          // latitude and longitude stitching
          location: longitude + ', ' + latitude,
          // Map markers, copied from the course
          markers: [{
            id: "0".latitude: latitude,
            longitude: longitude,
            iconPath: "/static/images/location.png".width: 40.height: 40.callout: {
              'display': 'ALWAYS'.'fontSize': '30rpx'.'content': 'I'm here'.'padding': '8rpx'.'boxShadow': '0 0 5rpx #333'.'borderRadius':'4rpx'}}}])// Get data for three days, save data to data after success
        HFAPI.threeDays({
          location: that.data.location
        }).then(res= > {
          if (res.code === '200') that.setData({
            threeDays: res.daily
          })
        })
      }
    })

  },

  /** * lifecycle function - listen for the page to complete the first rendering */
  onReady: function () {},/** * lifecycle function -- listens for page display */
  onShow: function () {},/** * life cycle function - listen for page hiding */
  onHide: function () {},/** * life cycle function - listen for page unload */
  onUnload: function () {},/** * page-related event handlers -- listen for user pull actions */
  onPullDownRefresh: function () {},/** * the handler for the pull-down event on the page */
  onReachBottom: function () {},/** * Users click on the upper right corner to share */
  onShareAppMessage: function () {}})Copy the code

Function Combination (1)

  • Combine data interfaces and project interfaces
  • Add criteria to determine whether data is obtained successfully. Set data. Otherwise, a message will be displayed
  • Iterate over the obtained weather data for three days, create a list structure, see more don’t
  • If no name is set, item is used by default
  • The picture given by Zephyr weather is coded, which needs to be downloaded and used by ourselves, and then spliced
<! --pages/qweather/qweather.wxml-->
<view class="container">
  <! -- Top map, set latitude and longitude, mark, zoom scale -->
  <map name="" longitude='{{longitude}}' latitude='{{latitude}}' markers='{{markers}}' scale="14"
    style="width: 100%; height: 160px"></map>
  <! -->
  <view class="weui-panel weui-panel_access">
    <view class="weui-panel__hd">Combination list</view>
    <view class="weui-panel__bd">
      <! Wx :for - wx:for - wx:key - set key -->
      <a class="weui-media-box weui-media-box_appmsg" wx:for="{{threeDays}}" wx:key='abc'>
        <view class="weui-media-box__hd">
          <! You use zephyr weather to provide icon library -->
          <image class="weui-media-box__thumb" src=".. /.. /static/hfIcon/{{item.iconDay}}.png" alt></image>
        </view>
        <view class="weui-media-box__bd">
          <! -- Bind data -->
          <h4 class="weui-media-box__title">{{item.fxDate}}</h4>
          <view class="weui-media-box__desc">Maximum temperature: {{item.tempmax}} - Minimum temperature: {{item.tempmin}}</view>
        </view>
      </a>
    </view>
  </view>
</view>

<! SRC property: template file path -->
<import src='.. /.. /tpl/my-footer'></import>
<! --> < span style = "color: RGB (51, 51, 51);
<template is='my-footer' data=' '></template>
Copy the code

Function Combination (2)

WXML template

Some common page structures, such as headers, footers, and other information, are the same. You can use the template function to create templates and call them on the required page

<! Create template -->
<template name='my-footer'>
<! -- Template content -->
  <view class="weui-footer weui-footer_fixed-bottom">
			<view class="weui-footer__links">
				<a href="javascript:home();" class="weui-footer__link">Thanks for the mild weather</a>
			</view>
			<view class="weui-footer__text">Pull Education provides support</view>
		</view>
</template>
Copy the code
<! Use the template at the bottom of the WXML file.<! SRC property: template file path -->
<import src='.. /.. /tpl/my-footer'></import>
<! --> < span style = "color: RGB (51, 51, 51);
<template is='my-footer' data=' '></template>
Copy the code

Mobile client API

For example, functions such as taking photos and scanning need to be invoked on the mobile terminal, but cannot be invoked on the Web terminal

<! --index.wxml-->
<view class="container">
  <! -- Go to photo button -->
  <button type="primary" bindtap="toCamear">To take pictures</button>
  <! -- Scan the button -->
  <button type="primary" bindtap="bindScan">scan</button>
  <! Show the result of the scan -->
  <text>{{scanResult}}</text>
</view>
Copy the code
// index.js
// Get the application instance
const app = getApp()

Page({
  data: {
    // Scan the result
    scanResult: ' '. },...// Jump to the photo page
  toCamear: () = > {
    // Applet API
    wx.navigateTo({
      // Jump to the page
      url: 'camear',}}),// Invoke the sweep interface
  bindScan: function() {
    // wechat scan API
    wx.scanCode({
      // called after success
      success: (res) = > {
        console.log(res)
        // Modify the data
        this.setData({
          scanResult: res.result
        })
      }
    })
  },
})
Copy the code
<! --pages/index/camear.wxml-->
<view class="swiper-view">
  <! -- Camera component -->
  <camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 200px;"></camera>
  <! -- Photo button -->
  <button type="default" bindtap="takePhoto" style="margin: 20px 0; width: 100%;">Taking pictures</button>
  <view style="margin: 20rpx; ">
    <! -- Photo preview -->
    <image mode="widthFix" src="{{src}}" style="width: 100%; border-radius: 60rpx;"></image>
  </view>
</view>
Copy the code
// pages/test/camera.js
Page({

  /** * initial data for the page */
  data: {},.../ / photo
  takePhoto() {
    // Create a photo context - applet API
    const ctx = wx.createCameraContext()
    // Start taking photos
    ctx.takePhoto({
      // Shooting quality
      quality: 'high'.// called after success
      success: (res) = > {
        // Save the address
        this.setData({
          src: res.tempImagePath
        })
      }
    })
  },
})
Copy the code

Apply to amap as a developer