Home  >  Article  >  WeChat Applet  >  Analysis of WeChat applet front-end source code

Analysis of WeChat applet front-end source code

不言
不言Original
2018-06-27 17:35:031861browse

This article mainly introduces relevant information about the detailed explanation and example analysis of the front-end source code of WeChat Mini Program. Friends who need it can refer to

WeChat Mini Program front-end source code logic and workflow

Finishing the front-end code of the WeChat applet really made my blood boil. The code logic and design are clear at a glance, there are no superfluous things, it is really simple.

Without further ado, let’s analyze the front-end code directly. Personal opinions, there may be some omissions, it is for reference only.

Basic structure of the file:

First look at the entrance app.js, app (obj) registers a small program. Accepts an object parameter, which specifies the life cycle function of the applet, etc. Other files can obtain the app instance through the global method getApp(), and then directly call its properties or methods, such as (getApp().globalData)

##

//app.js
App({
 onLaunch: function () {
  //调用API从本地缓存中获取数据
  var logs = wx.getStorageSync('logs') || []
  logs.unshift(Date.now())
  wx.setStorageSync('logs', logs)
 },
 getUserInfo:function(cb){
  var that = this
  if(this.globalData.userInfo){
   typeof cb == "function" && cb(this.globalData.userInfo)
  }else{
   //调用登录接口
   wx.login({
    success: function () {
     wx.getUserInfo({
      success: function (res) {
       that.globalData.userInfo = res.userInfo
       typeof cb == "function" && cb(that.globalData.userInfo)
      }
     })
    }
   })
  }
 },
 globalData:{
  userInfo:null
 }
})

I understand that app.js is the entry initialization file and is also where global API expansion is provided. Let’s analyze the several methods and attributes that come with it

onLaunch hook function will be automatically executed once after the mini program initialization is completed, and then if you do not actively call it during the mini program life cycle onLaunch, it will not be executed.

var logs = wx.getStorageSync('logs') || [] Get the logs attribute in the local cache. If the value is empty, set logs=[] and have a similar effect to localStorage in HTML5

logs.unshift(Date.now()) Add the current login time to the array

wx.setStorageSync('logs', logs) Store the data in the local cache, because wx is a global object, so You can directly call wx.getStorageSync('logs') in other files to obtain local cache data


getUserInfo function,As the name suggests, it is to obtain logged-in user information, which is equivalent to this function providing The interface for obtaining user information will not be executed unless called by other pages. Other pages call this method through getApp().getUserInfo(function(userinfo){console.log(userinfo);}) to obtain user information.

getUserInfo:function(cb){//参数为cb,类型为函数
  var that = this
  if(this.globalData.userInfo){//用户信息不为空
   typeof cb == "function" && cb(this.globalData.userInfo)//如果参数cb的类型为函数,那么执行cb,获取用户信息;
  }else{//如果用户信息为空,也就是说第一次调用getUserInfo,会调用用户登录接口。
   wx.login({
    success: function () {
     wx.getUserInfo({
      success: function (res) {
         console.log(res)
       that.globalData.userInfo = res.userInfo//把用户信息赋给globalData,如果再次调用getUserInfo函数的时候,不需要调用登录接口
       typeof cb == "function" && cb(that.globalData.userInfo)//如果参数cb类型为函数,执行cb,获取用户信息
      }
     })
    }
   })
  }
 }

globalData object is used to store global data, and is called

in other places and then briefly analyze it app.json file, the function of this file is to globally configure the WeChat applet, determine the path of the page file, window performance, set network timeout, set multiple tabs, etc.

The most important thing is

pages attribute, required, is an array. The elements in the array are string file paths, specifying which pages the mini program consists of. The first item must be the initial page of the mini program.

{
 "pages":[
  "pages/index/index",
  "pages/logs/logs"
 ],
 "window":{
  "backgroundTextStyle":"light",
  "navigationBarBackgroundColor": "#fff",
  "navigationBarTitleText": "WeChat",
  "navigationBarTextStyle":"black"
 }
}

Then take a look at the project index and logs folders. The initial WeChat applet project puts the js, wxss, and wxml related to each page in their own files, so that the structure looks much clearer.

Let’s first look at the index folder, which is the initial page of the mini program. Under the index folder are three small files: index.js, index.wxml, and index.wxss. The mini program separates js, css, and html codes and puts them in separate files, each performing its own duties. The js and style sheet file names must be consistent with the wxml file name of the current folder, so as to ensure that the effects of js and style sheets can be displayed on the page. I appreciate this kind of design concept, which is neat and uniform, with clear responsibilities, and reduces the complexity of code design.

 

Index.wxml, this is a common template file, data-driven. Those who have developed front-end mvc and mvvm projects will be familiar with this. After all, it is developed based on react.​

<!--index.wxml-->
<view class="container">//视图容器
 <view bindtap="bindViewTap" class="userinfo">//bindtap为容器绑定点击触摸事件,在触摸离开时触发bindViewTap事件处理函数,bindViewTap通过index.js page()设置添加
  <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>//大双括号的变量来自于index.js的data对象解析成对应的值,而且是实时的
  <text class="userinfo-nickname">{{userInfo.nickName}}</text>
 </view>
 <view class="usermotto">
  <text class="user-motto">{{motto}}</text>
 </view>
</view>

index.js, the usage is almost the same as reaact, changing the soup without changing the medicine. page() to register a page. Accepts an OBJECT parameter, which specifies the page's initial data, life cycle functions, event handling functions, etc.

var app = getApp() // 获取入口文件app的应用实例
Page({
 data: {
  motto: &#39;Hello World&#39;,
  userInfo: {}
 },
 //自定义事件处理函数,点击.userinfo的容易触发此函数
 bindViewTap: function() {
  wx.navigateTo({//全局对象wx的跳转页面方法
   url: &#39;../logs/logs&#39;
  })
 },
 onLoad: function () {//发生页面加载时,自动触发该生命周期函数
  console.log(&#39;onLoad&#39;)
  var that = this
  //调用应用实例的方法获取全局数据
  app.getUserInfo(function(userInfo){
   //更新数据,页面自动渲染
   that.setData({
    userInfo:userInfo
   })
  })
 }
})

The index.wxss file only renders the current page it belongs to, and will overwrite the same style of the global app.wxss.

Analyze the logs log folder again. The logs folder contains logs.wxml, logs.js, logs.wxss, and logs.json. In the same way, ensure the same name to complete the effect rendering.

 logs.wxml file

<!--logs.wxml-->
<view class="container log-list">
 <block wx:for="{{logs}}" wx:for-item="log">//block容器作用,无其他实际含义。wx:for作用:遍历logs数组,遍历多少次,block块就会复制多少次,for-item等同于为<br>遍历元素起一个变量名,方便引用。<br>
  <text class="log-item">{{index + 1}}. {{log}}</text>
 </block>
</view>

 logs.js file

//logs.js
var util = require(&#39;../../utils/util.js&#39;) //util.js相当于一个函数库,我们可以在这个文件内自定义扩展和封装一些常用的函数和方法
Page({
 data: {
  logs: []
 },
 onLoad: function () {
  this.setData({
   logs: (wx.getStorageSync(&#39;logs&#39;) || []).map(function (log) {//通过wx.getStorageSync获取本地缓存的logs日志数据
    return util.formatTime(new Date(log))//日期格式化
   })
  })
 }
})

 logs.json file

{
  "navigationBarTitleText": "查看启动日志"  //当前页面配置文件,设置window当前页面顶部导航栏标题等相关内容
}  

The basic page structure and logic are so simple, and there is nothing puzzling exposed to us.

The mini program also provides many official components and APIs waiting for us to dig deeper, come on, boy!

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to implement the WeChat mini program tab

WeChat applet implements drag and drop image touch event monitoring

The DVA framework uniformly handles the loading status of all pages

The above is the detailed content of Analysis of WeChat applet front-end source code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn