Let's learn WeChat applet api together

WeChat applet api introduction

The Mini Program API is the core of Mini Program development. Through the API, developers can obtain the advanced features encapsulated in the bottom layer of WeChat, such as network requests, file operations, device information, geographic location, local storage, etc.
The API of the applet uses the global object wx as the namespace, and the format is wx.method name(), which can be called globally.

Next, I will introduce a few commonly used apis api的基础, 路由, 网络请求, 界面, 用户信息, 上传, 下载, 开放接口
and before introducing the editor’s suggestion, if you want to master the small program api, you must learn to read the WeChat development documentation to use it! ! !

api-basics

  • wx.getSkylineInfoSync() Obtain system information
    windowHeight available window height
    windowWidth available window width
    statusBarHeight status bar height
    safeArea safe area in the positive direction of the vertical screen
    model phone model
    system operating system and version
    benchmarkLevel power

We can get the system information of wxml in wxjs

//wxml代码
<view class="title">基础</view>
<view>wx.getSystemInfoSync() 同步获取系统信息</view>
//wxjs代码
 //生命周期函数--监听页面加载
  onLoad(options) {
    
    
    var sys = wx.getSystemInfoSync();
    console.log(sys)
  },

Details can be seen in the diagram
insert image description here

Mini Program Routing

Routing Development Documentation

The program is a single page, and the switching of pages is essentially a partial update, which is actually implemented by routing. However, the routes of the applet are encapsulated by default, the menu configured at the bottom, and the navigator label.

(The routing editor has a more detailed introduction in the previous article)

  • wx.navigateTo({}) Jump
    • Keep the current page and jump to a page in the app. But can not jump to the tabbar page. Use wx.navigateBack to return to the original page. The page stack in the applet has a maximum of ten layers.
  • wx.redirectTo() redirection
    • Close the current page and jump to a page in the app. But jumping to the tabbar page is not allowed.
  • wx.switchTab() toggle bottom bar
    • Jump to the tabBar page and close all other non-tabBar pages
  • wx.navigateBack( ) return
<navigator url="/pages/home/home.js">home</navigator>
<navigator url="/pages/home/home.js" open-type="redirect">首页-redirect</navigator>

network

1. Network request wx.request (I also have a more detailed introduction in the previous article)

Here the editor emphasizes several common parameters
urlRequest address (required)
dataData (post)
headerRequest header information
timeoutTimeout
methodsmethod post | get | put |
successsuccess callback function
failThe callback function that fails the interface call
completeis completed (both success and failure will be executed) and will end loading prompt

2. Download wx.downloadFile()

Download the file resource to the local. The client directly initiates an HTTPS GET request and returns the local temporary path (local path) of the file. The maximum file size allowed for a single download is
200MB.

//wxml代码
<view class="title">wx.downloadFile 下载文件</view>
<view class="title">wx.saveImageToPhotosAlbum 保存图片到相册</view>
<image src="{
    
    {pic}}" mode="aspectFill" bindtap="downPic"></image>
//js代码
downPic(){
    
    
    wx.downloadFile({
    
    
      url: this.data.pic,
      success(res){
    
    
        console.log(res);
        // 把临时文件保存到相册(需要用户授权) 
        // 当点击下载时会弹出是否允许访问您的相册 同意则可下载
        wx.saveImageToPhotosAlbum({
    
    
          filePath: res.tempFilePath,
          success(){
    
    
            // 提示保存成功
            wx.showToast({
    
    
              title: '下载图片成功',
              icon:"none"
            })
          }
        })
      }
    })
  },

renderings
insert image description here

3. Upload wx.uploadFile
Here you can refer to 媒体相关wx.chooseImage
Choose a picture from the album
chooseMessageFile choose a picture or video

Upload local resources to the server. The client initiates an HTTPS POST request, where the content-type is multipart/form-data.

//wxml代码
<button type="warn" bindtap="upImg">上传图片</button>
<view class="title">wx.uploadFile 上传</view>
<view class="title">wx.chooseMedia 选择图片或者视频</view>
<view class="title"> wx.chooseImage 从相册选择图片</view>
//js代码
 upImg(){
    
    
    var that  =  this;
    // 选择图片
    // wx.chooseImage({
    
    
    // 选择媒体
    wx.chooseMedia({
    
    
      count: 1, //媒体数量
      success(res){
    
    
        console.log(res)
        // 获取选择的第0个图片临时地址
        var tempFile = res.tempFiles[0].tempFilePath;
        wx.uploadFile({
    
    
          filePath: tempFile,
          name: 'file',
          url: 'http://dida100.com/ajax/file.php',
          success:res=>{
    
    
            console.log(res);
            // 转换为js对象
            var data = JSON.parse(res.data);
            // 更新图片信息
            that.setData({
    
    pic:"http://dida100.com"+data.pic})
          }
        })
      }
    })
  },

renderings
insert image description here

interface

Introduce several commonly used wx.showToast, wx.showModal, wx.showLoading, wx.setNavigationBarTitle1. wx.setNavigationBarColor
Interaction

//wxml代码
<button size="mini" bindtap="showTip">提示</button>
//js代码
showTip(){
    
    
    // setNavigationBarTitle 标题栏文本
    wx.setNavigationBarTitle({
    
    
      title: 'api讲解',
    })
    wx.showToast({
    
    
      title: '你好!',
      icon:"none"
    })
     },

renderings
insert image description here

//wxml代码
<button size="mini" bindtap="showTip">提示</button>
//js代码
showTip(){
    
    
    // setNavigationBarTitle 标题栏文本
    wx.setNavigationBarTitle({
    
    
      title: 'api讲解',
    })
   
    wx.showToast({
    
    
      title: '你好!',
      icon:"none"
    })

renderings
insert image description here

//wxml代码
<button size="mini" bindtap="showTip">提示</button>
//js代码
showTip(){
    
    
    // setNavigationBarTitle 标题栏文本
    wx.setNavigationBarTitle({
    
    
      title: 'api讲解',
    })
    
    // wx.showLoading 加载提示
    wx.showLoading({
    
    
      title: '加载中...',
    })
    setTimeout(()=>{
    
    
      wx.hideLoading();
    },2000)
  },

renderings
insert image description here

2. Navigation bar

//wxml代码
<button size="mini" bindtap="showTip">提示</button>
//js代码
showTip(){
    
    
    // setNavigationBarTitle 标题栏文本
    wx.setNavigationBarTitle({
    
    
      title: 'api讲解',
    })
    // setNavigationBarColor 设置导航栏的颜色
    wx.setNavigationBarColor({
    
    
      frontColor: '#ffffff',
      backgroundColor: '#000000',
      animation: {
    
    
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
   }

renderings
insert image description here

open interface

1. wx.getUserProfile user information

Get user information. It can only be called after the page generates a click event (for example, in the callback of bindtap on the button), and an authorization window will pop up for each request, and userInfo will be returned after the user agrees. This interface is used to replace wx.getUserInfo

//wxml代码
<view class="title">开放能力</view>
<view>wx.getUserProfile 获取用户信息</view>
<view wx:if="{
    
    {userInfo.nickName}}">
  <image style="width: 100px; height: 100px;" src="{
    
    {userInfo.avatarUrl}}"></image>
  <view>{
    
    {
    
    userInfo.nickName}}</view>
</view> 
<button wx:else size="mini" bindtap="getUser">获取用户信息</button>
//js代码
 onLoad(options) {
    
    
    var sys = wx.getSystemInfoSync();
    console.log(sys);
    // 本地获取用户信息
    var userInfo = wx.getStorageSync('userInfo')||{
    
    };
    // 更新用户信息
    this.setData({
    
    userInfo})
  },
  getUser(){
    
    
    var that = this;
    wx.getUserProfile({
    
    
      desc: '需要获取您的昵称',
      success:res=>{
    
    
        console.log(res);
        // 更新本地用户信息
        that.setData({
    
    "userInfo":res.userInfo})
        // 存储用户信息到本地
        wx.setStorageSync('userInfo', res.userInfo)
      }
    })
  },

insert image description here
end...
Every step of the article can jump to the official document for easy search.
Remember to be familiar with the official Q&A is the most important! ! !
I hope the article can help you who are studying.
See you in the next issue~

Guess you like

Origin blog.csdn.net/promise466/article/details/127858606