


Detailed explanation of WeChat applet front-end source code and example analysis
Mar 20, 2017 am 09:42 AMThis article mainly introduces WeChat Mini Program Detailed explanation of front-end source code and related information of example analysis. Friends in need can refer to
WeChat Mini Program front-end source code logic and workflow
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, register one app (obj) Applets. Accepts an object parameter, which specifies the life cyclefunction etc. of the applet. 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, then set logs=[] and HTML5 localStorage has a similar function
logs.unshift(Date.now()) The current login time is added to the array
wx.setStorageSync('logs', logs) The data Store it in the local cache. Because wx is a global object, you can directly call wx.getStorageSync('logs') in other files to obtain the local cache data
getUserInfo function, As the name suggests, it is to obtain the 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){//參數(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,會調(diào)用用戶登錄接口。 wx.login({ success: function () { wx.getUserInfo({ success: function (res) { console.log(res) that.globalData.userInfo = res.userInfo//把用戶信息賦給globalData,如果再次調(diào)用getUserInfo函數(shù)的時候,不需要調(diào)用登錄接口 typeof cb == "function" && cb(that.globalData.userInfo)//如果參數(shù)cb類型為函數(shù),執(zhí)行cb,獲取用戶信息 } }) } }) } }
The globalData object is used to store global data. Call
in other places and then briefly analyze the app.json file. The function of the file is to globally configure the WeChat applet, determine the path of the page file, window performance, set the network timeout, set multiple tabs, etc.
The most important thing is the pages attribute, required, is an array. The elements in the array are strings 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 look at the project index and logs folders. The initial project of the WeChat applet 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, datadriver, those who have developed front-endmvc, 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)擊觸摸事件,在觸摸離開時觸發(fā)bindViewTap事件處理函數(shù),bindViewTap通過index.js page()設(shè)置添加 <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>//大雙括號的變量來自于index.js的data對象解析成對應(yīng)的值,而且是實(shí)時的 <text class="userinfo-nickname">{{userInfo.nickName}}</text> </view> <view class="usermotto"> <text class="user-motto">{{motto}}</text> </view> </view>
index.js,與reaact用法幾無二異,換湯不換藥。page()來注冊一個頁面。接受一個 OBJECT 參數(shù),其指定頁面的初始數(shù)據(jù)、生命周期函數(shù)、事件處理函數(shù)等。
var app = getApp() // 獲取入口文件app的應(yīng)用實(shí)例 Page({ data: { motto: 'Hello World', userInfo: {} }, //自定義事件處理函數(shù),點(diǎn)擊.userinfo的容易觸發(fā)此函數(shù) bindViewTap: function() { wx.navigateTo({//全局對象wx的跳轉(zhuǎn)頁面方法 url: '../logs/logs' }) }, onLoad: function () {//發(fā)生頁面加載時,自動觸發(fā)該生命周期函數(shù) console.log('onLoad') var that = this //調(diào)用應(yīng)用實(shí)例的方法獲取全局?jǐn)?shù)據(jù) app.getUserInfo(function(userInfo){ //更新數(shù)據(jù),頁面自動渲染 that.setData({ userInfo:userInfo }) }) } })
index.wxss文件只渲染當(dāng)前所屬頁面,會覆蓋全局app.wxss同一樣式。
再分析下logs日志文件夾,logs文件夾下為logs.wxml、logs.js、logs.wxss、logs.json,同理保證同名,才能完成效果渲染。
logs.wxml文件
<!--logs.wxml--> <view class="container log-list"> <block wx:for="{{logs}}" wx:for-item="log">//block容器作用,無其他實(shí)際含義。wx:for作用:遍歷logs數(shù)組,遍歷多少次,block塊就會復(fù)制多少次,for-item等同于為<br>遍歷元素起一個變量名,方便引用。<br> <text class="log-item">{{index + 1}}. {{log}}</text> </block> </view>
logs.js 文件
//logs.js var util = require('../../utils/util.js') //util.js相當(dāng)于一個函數(shù)庫,我們可以在這個文件內(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文件
{ "navigationBarTitleText": "查看啟動日志" //當(dāng)前頁面配置文件,設(shè)置window當(dāng)前頁面頂部導(dǎo)航欄標(biāo)題等相關(guān)內(nèi)容 }
基本頁面結(jié)構(gòu)和邏輯就這么簡單,暴露給我們的沒有一點(diǎn)令人費(fèi)解的東西。
更多Detailed explanation of WeChat applet front-end source code and example analysis相關(guān)文章請關(guān)注PHP中文網(wǎng)!
相關(guān)文章:
微信官方開發(fā)者工具如何導(dǎo)入小程序源碼demo
The above is the detailed content of Detailed explanation of WeChat applet front-end source code and example analysis. 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

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include
