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 () { //調(diào)用API從本地緩存中獲取數(shù)據(jù) 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{ //調(diào)用登錄接口 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 HTML5logs.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){//參數(shù)為cb,類型為函數(shù) var that = this if(this.globalData.userInfo){//用戶信息不為空 typeof cb == "function" && cb(this.globalData.userInfo)//如果參數(shù)cb的類型為函數(shù),那么執(zhí)行cb,獲取用戶信息; }else{//如果用戶信息為空,也就是說第一次調(diào)用getUserInfo,會(huì)調(diào)用用戶登錄接口。 wx.login({ success: function () { wx.getUserInfo({ success: function (res) { console.log(res) that.globalData.userInfo = res.userInfo//把用戶信息賦給globalData,如果再次調(diào)用getUserInfo函數(shù)的時(shí)候,不需要調(diào)用登錄接口 typeof cb == "function" && cb(that.globalData.userInfo)//如果參數(shù)cb類型為函數(shù),執(zhí)行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 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. 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為容器綁定點(diǎn)擊觸摸事件,在觸摸離開時(shí)觸發(fā)bindViewTap事件處理函數(shù),bindViewTap通過index.js page()設(shè)置添加 <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>//大雙括號(hào)的變量來自于index.js的data對(duì)象解析成對(duì)應(yīng)的值,而且是實(shí)時(shí)的 <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的應(yīng)用實(shí)例 Page({ data: { motto: 'Hello World', userInfo: {} }, //自定義事件處理函數(shù),點(diǎn)擊.userinfo的容易觸發(fā)此函數(shù) bindViewTap: function() { wx.navigateTo({//全局對(duì)象wx的跳轉(zhuǎn)頁面方法 url: '../logs/logs' }) }, onLoad: function () {//發(fā)生頁面加載時(shí),自動(dòng)觸發(fā)該生命周期函數(shù) console.log('onLoad') var that = this //調(diào)用應(yīng)用實(shí)例的方法獲取全局?jǐn)?shù)據(jù) app.getUserInfo(function(userInfo){ //更新數(shù)據(jù),頁面自動(dòng)渲染 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容器作用,無其他實(shí)際含義。wx:for作用:遍歷logs數(shù)組,遍歷多少次,block塊就會(huì)復(fù)制多少次,for-item等同于為<br>遍歷元素起一個(gè)變量名,方便引用。<br> <text class="log-item">{{index + 1}}. {{log}}</text> </block> </view>logs.js file
//logs.js var util = require('../../utils/util.js') //util.js相當(dāng)于一個(gè)函數(shù)庫,我們可以在這個(gè)文件內(nèi)自定義擴(kuò)展和封裝一些常用的函數(shù)和方法 Page({ data: { logs: [] }, onLoad: function () { this.setData({ logs: (wx.getStorageSync('logs') || []).map(function (log) {//通過wx.getStorageSync獲取本地緩存的logs日志數(shù)據(jù) return util.formatTime(new Date(log))//日期格式化 }) }) } })logs.json file
{ "navigationBarTitleText": "查看啟動(dòng)日志" //當(dāng)前頁面配置文件,設(shè)置window當(dāng)前頁面頂部導(dǎo)航欄標(biāo)題等相關(guān)內(nèi)容 }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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

H5 development tools recommendations: VSCode, WebStorm, Atom, Brackets, Sublime Text; Mini Program Development Tools: WeChat Developer Tools, Alipay Mini Program Developer Tools, Baidu Smart Mini Program IDE, Toutiao Mini Program Developer Tools, Taro.

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.

The best cryptocurrency trading and analysis platforms include: 1. OKX: the world's number one in trading volume, supports multiple transactions, provides AI market analysis and on-chain data monitoring. 2. Binance: The world's largest exchange, providing in-depth market conditions and new currency first-time offerings. 3. Sesame Open Door: Known for spot trading and OTC channels, it provides automated trading strategies. 4. CoinMarketCap: an authoritative market data platform, covering 20,000 currencies. 5. CoinGecko: Known for community sentiment analysis, it provides DeFi and NFT trend monitoring. 6. Non-small account: a domestic market platform, providing analysis of linkage between A-shares and currency markets. 7. On-chain Finance: Focus on blockchain news and update in-depth reports every day. 8. Golden Finance: 24 small

The login portal for the Douyin web version is https://www.douyin.com/. The login steps include: 1. Open the browser; 2. Enter the URL https://www.douyin.com/; 3. Click the "Login" button and select the login method; 4. Enter the account password; 5. Complete login. The web version provides functions such as browsing, searching, interaction, uploading videos and personal homepage management, and has advantages such as large-screen experience, multi-tasking, convenient account management and data statistics.

10 top scams on cryptocurrency exchanges Common scams: fake exchanges, Ponzi capital trading, contract manipulation, fake coin phishing, customer service fraud, etc. Identification points: Check regulatory licenses, check contract addresses, and be wary of high-yield commitments Must be protected: Use only mainstream exchanges (Binance/Coinbase) Enable hardware wallet Reject share private key/verification code Deal with fraud: take screenshots immediately, freeze assets, report on the platform, and report to the police Core principle: Any request for password/transfer is a fraud!
