Three examples of WeChat applets to get you started

Three examples of WeChat applets to get you started

pre-declaration

  1. When creating a new WeChat applet project, the cloud development service is used by default (you can turn it off if you don’t need cloud development)

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-V2Z5HIyl-1595050183309)(en-resource://database/501:1)]

  1. Project directory and file meaning View WeChat official documents

  2. App.json part highlights
    [External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-opsmnfuD-1595050183314)(en-resource://database/503:1)]

develop a default page

We create a new componet folder, create a new submit folder in the componet, and finally create a new page named submit. The results are as follows.
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-7Zk3AvU9-1595050183315)(en-resource://database/507:1)]

Then configure a default page "componet/submit/submit" in app.json.

Finally, configure the loading data in submit.js, configure the navigation bar and tab bar data in submit.json, configure the page structure in wxml, configure the structure style in wxss, ctrl+s or directly save and run, the results are as follows.

Develop a single page with dynamically changing data (take user authorization as an example)

Effect picture display:
insert image description here
Explanation:

We can reassign the data in the form of this.setData({key:value}) in the onload loading method or in any custom binding function or listening function, and then the data will be dynamically presented on the page. The userInfo object data obtained by winning the prize in this example is displayed on a single page, and the source code is displayed.
js source code:


const app = getApp()
Page({
    
    
  data: {
    
    
    //判断小程序的API,回调,参数,组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    userInfo:{
    
    },
    haveUser:false
  },
  onLoad: function () {
    
    
    var that = this;
    // 查看是否授权
    wx.getSetting({
    
    
      success: function (res) {
    
    
        if (res.authSetting['scope.userInfo']) {
    
    
          wx.getUserInfo({
    
    
            success: function (res) {
    
    
           
              wx.login({
    
    
                success: res => {
    
    
                  // 获取到用户的 code 之后:res.code
                  console.log("用户的code:" + res.code);
                  // 可以传给后台,再经过解析获取用户的 openid
                  // 或者可以直接使用微信的提供的接口直接获取 openid ,方法如下:
                  // wx.request({
    
    
                  //     // 自行补上自己的 APPID 和 SECRET
                  //     url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
                  //     success: res => {
    
    
                  //         // 获取到用户的 openid
                  //         console.log("用户的openid:" + res.data.openid);
                  //     }
                  // });
                }
              });
            }
          
          });
      
        } else {
    
    
          // 用户没有授权
          // 改变 isHide 的值,显示授权页面
          that.setData({
    
    
            isHide: true
          });
        }
      }
    });
  },
  bindGetUserInfo: function (e) {
    
    
    if (e.detail.userInfo) {
    
    
      //用户按了允许授权按钮
      var that = this;
      // 获取到用户的信息了,打印到控制台上看下
      app.globalData.userInfo = e.detail.userInfo;
      //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
      that.setData({
    
    
        isHide: false,
        haveUser:true,
        userInfo:e.detail.userInfo
      });
   
    } else {
    
    
      //用户按了拒绝按钮
      wx.showModal({
    
    
        title: '警告',
        content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
    
    
          // 用户没有授权成功,不需要改变 isHide 的值
          if (res.confirm) {
    
    
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  }
})

A reminder is needed: this is only available at the outermost layer in the above functions. If a function is nested in a function, this in the nested function represents the nested function. Solution: declare and use that to represent the app itself var that = this.

json source code:


{
    
    
  "navigationBarTitleText": "登录"
}


wxss source code:


 
.header {
    
    
    margin: 90rpx 0 90rpx 50rpx;
    border-bottom: 1px solid #ccc;
    text-align: center;
    width: 650rpx;
    height: 300rpx;
    line-height: 450rpx;
}
 
.header image {
    
    
    width: 200rpx;
    height: 200rpx;
}
 
.content {
    
    
    margin-left: 50rpx;
    margin-bottom: 90rpx;
}
 /**index.wxss**/
.userinfo {
    
    
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .userinfo-avatar {
    
    
    width: 128rpx;
    height: 128rpx;
    margin: 20rpx;
    border-radius: 50%;
  }
  
  .userinfo-nickname {
    
    
    color: #aaa;
  }
  
  .usermotto {
    
    
    margin-top: 200px;
  }
.content text {
    
    
    display: block;
    color: #9d9d9d;
    margin-top: 40rpx;
}
 
.bottom {
    
    
    border-radius: 80rpx;
    margin: 70rpx 50rpx;
    font-size: 35rpx;
}


wxml source code:


<view wx:if="{
     
     {isHide}}">
    <view wx:if="{
     
     {canIUse}}" >
        <view class='header'>
            <image src='/images/template/1.jpg'></image>
        </view>
 
        <view class='content'>
            <view>申请获取以下权限</view>
            <text>获得你的公开信息(昵称,头像等)</text>
        </view>
 
        <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo">
            授权登录
        </button>
    </view>
    <view wx:else>请升级微信版本</view>
</view>
<view class="userinfo" wx:if="{
     
     {haveUser}}">
    <block >
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{
     
     {userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{
   
   {userInfo.nickName}}</text>
    </block>
</view>


There are many tags in wxml that can be bound to events (see the api documentation). I often use bindtap, catchsubmit, catchreset to achieve binding

Develop an instance of data transfer between pages

We all know that http requests include: post get head patch options put delete trace connect
commonly used ones post get, and the corresponding implementation method in the WeChat applet is the global url link. I will introduce both of these.

A URL is passed.
We can use navigator (similar to the a tag in html) to realize the jump, which can carry parameters when jumping. We can also use wx.navigatorto in the binding event to realize the jump, please check the api document for binding . Parameters can be implemented using form, there is not much involved here, check the document by yourself

The URL transfer source code is attached:
login.wxml


<!--login.wxml-->
<view class="container">
 <!-- 使用navigator组件 -->
 <navigator url="pages/index/index?title=我是传递值">传递</navigator>
</view>

index.js

// pages/index/index.js
Page({
    
    
 
 data: {
    
    
 title:''
 },
 
 onLoad: function (options) {
    
    
 console.log(options) //打印options,可以看到title的值可以获取到
 this.setData({
    
    
 title:options.title //为页面中title赋值
 })
 },
})

index.html

<view class='container'>
 {
   
   {title}}
</view>

Two global transfers

The data saved globally must meet the needs of the entire applet. For example, a video playback applet requires user information, but a video information does not need to be saved, otherwise the global cache of the entire applet will increase rapidly. , seriously causing downtime. Not much to say, the source code is attached.
app.js

//app.js
App({
    
    
 globalData: {
    
    }
})

index.wxml

<!--index.wxml-->
<!-- 点击触发go_Demo函数 -->
<view class="container" bindtap='go_Demo'>
 传递
</view>

index.js

//index.js
//获取应用实例
const app = getApp()
Page({
    
    
 data: {
    
    
 title:'参数传递'
 },
 go_Demo: function() {
    
    
 app.globalData.title = this.data.title
 wx.navigateTo({
    
    
 url: '../demo/demo',
 })
 }
})

demo.js


// pages/demo/demo.js
//获取应用实例
const app = getApp()
Page({
    
    
 data: {
    
    
 title:''
 },
 onLoad: function (options) {
    
    
 console.log(app.globalData.title) //打印options,可以看到title的值可以获取到
 this.setData({
    
    
 title: app.globalData.title //为页面中title赋值
 })
 },
})


For more information about WeChat Mini Programs 我的程序员提升专栏, please leave a message in the comment area if necessary.

Guess you like

Origin blog.csdn.net/weixin_44077556/article/details/107427723