WeChat applet front-end source code logic and workflow analysis
Reading the front-end code of the WeChat applet really makes 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.jsApp({ 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. It is also the place 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') || [] 获取本地缓存中的logs属性,如果值为空,那么设置logs=[] 与HTML5中的localStorage作用相似 logs.unshift(Date.now()) 当前登录时间添加到数组中 wx.getStorageSync('logs')获取本地缓存数据
getUserInfo function, as the name suggests, is to obtain logged-in user information. This function is equivalent to providing an interface for obtaining user information. Other pages will not be executed unless called. 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. Call
in other places and then briefly analyze the app.json file. The function of this file is Configure the WeChat applet globally, determine the path of the page file, window performance, set network timeout, set multiple tabs, etc.
The most important thing ispages 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, with a front-endmvc、mvvm Project developers will be familiar with this, after all, it is developed based on react . ##
<!--index.wxml--> <view>//视图容器 <view> //bindtap为容器绑定点击触摸事件,在触摸离开时触发bindViewTap事件处理函数,bindViewTap通过index.js page()设置添加 <image></image> //大双括号的变量来自于index.js的data对象解析成对应的值,而且是实时的 <text>{{userInfo.nickName}}</text> </view> <view> <text>{{motto}}</text> </view> </view>
index.js is almost the same as reaact. page() to register a page. Accepts an OBJECT parameter, which specifies the initial data of the page, life cycle function, event handling function, etc.
var app = getApp() // 获取入口文件app的应用实例Page({ data: { motto: 'Hello World', userInfo: {} }, //自定义事件处理函数,点击.userinfo的容易触发此函数 bindViewTap: function() { wx.navigateTo({//全局对象wx的跳转页面方法 url: '../logs/logs' }) }, onLoad: function () {//发生页面加载时,自动触发该生命周期函数 console.log('onLoad') var that = this //调用应用实例的方法获取全局数据 app.getUserInfo(function(userInfo){ //更新数据,页面自动渲染 that.setData({ userInfo:userInfo }) }) } })
index.wxss file only renders the current page it belongs to, and will overwrite the same style of global app.wxss.
Let’s analyze the logslog folder, logs## The # folder is logs.wxml、logs.js、logs.wxss, logs.json, similarly ensure that they have 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等同于为 遍历元素起一个变量名,方便引用。 <text class="log-item">{{index + 1}}. {{log}}</text> </block> </view>logs.js file
//logs.js var util = require('../../utils/util.js') //util.js相当于一个函数库,我们可以在这个文件内自定义扩展和封装一些常用的函数和方法 Page({ data: { logs: [] }, onLoad: function () { this.setData({ logs: (wx.getStorageSync('logs') || []).map(function (log) { //通过wx.getStorageSync获取本地缓存的logs日志数据 return util.formatTime(new Date(log))//日期格式化 }) }) } })logs.json file
{ "navigationBarTitleText": "查看启动日志" //当前页面配置文件,设置window当前页面顶部导航栏标题等相关内容 }
基本页面结构和逻辑就这么简单,暴露给我们的没有一点令人费解的东西。
小程序还提供了很多官方组件和API等待我们深挖,加油吧,少年!小程序官方文档地址
推荐教程:《微信小程序》
The above is the detailed content of WeChat applet front-end source code logic and workflow analysis. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
