Recently began to understand the Weixin small program, although the small program has been out for a long time, just out of that time very hot, see a lot of technical articles about the small program, but now seems not so hot, anyway, we can still learn.
I. Understanding Wechat Small Procedures
1. Idea: The goal of the small program development framework is to enable developers to develop services with native APP experience in micro-letters in as simple and efficient a way as possible.
2. Framework: The core of the framework is a response data binding system. The whole system is divided into two view layers (View) and logical layer (App Service). The framework can keep data and view synchronized very simply. As data modification, only need to modify the data in the logical layer, the view layer will be updated accordingly.
3. Relevant information: debugging tools download Simple Course
After we have a preliminary understanding of these basic information, let's first look at the ultimate effect of TODOS as an application.
2. Demonstration of TODOS Application Function and Directory Structure
Functional demonstration:
Directory structure:
The main function modules are:
index page, new tasks, add and delete operations can be completed
los page, record the operation on index page
Now let's go into details.
3. Code Explanation
1. Simple configuration app.json file:
{ "pages":[ "pages/index/index", // Set the page path, the project opens to find the file under this path "pages/logs/logs" ], "window":{ // Set window representation for default pages "backgroundTextStyle":"light", "navigationBarBackgroundColor": "#fff", "navigationBarTitleText": "TODOS", "navigationBarTextStyle":"black" }, "tabBar": { // Set the performance of the bottom tab "borderStyle": "white", "backgroundColor": "#f5f5f5", "selectedColor": "#222", "list": [ // Correspond to the bottom two menu items; TODOS and LOGS { "pagePath": "pages/index/index", "text": "TODOS", "iconPath": "images/home.png", "selectedIconPath": "images/home-actived.png" }, { "pagePath": "pages/logs/logs", "text": "LOGS", "iconPath": "images/note.png", "selectedIconPath": "images/note-actived.png" } ] } }
2.app.js and app.wxss files
The App() function is used to register a small program. Accept an object parameter that specifies the life cycle function of the applet, etc. App() must be registered in app.js and cannot register more than one.
Sample code
App({ onLaunch: function() { // Do something initial when launch. }, onShow: function() { // Do something when show. }, onHide: function() { // Do something when hide. }, onError: function(msg) { console.log(msg) }, globalData: 'I am global data' })
There is no need to add any code to App({}) in this project, so there is only one App({}) in the file.
app.wxss file can set some global styles
page { height: 100%; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; }
3. Registration Page
The Page() function is used to register a page. Accept an object parameter that specifies the page's initial data, lifecycle functions, event handling functions, and so on.
I. Initialization data
// ===== Page Data Object===== data: { input: '', todos: [], leftCount: 0, allCompleted: false, logs: [], addOneLoading: false, loadingHidden: true, loadingText: '', toastHidden: true, toastText: '', clearAllLoading: false },
Initialize the data as the first rendering of the page. Data will be transferred from the logical layer to the rendering layer in the form of JSON. The data can be strings, numbers, Boolean values, objects, arrays.
The rendering layer can bind data through WXML.
<input class="new-todo" value="{{ input }}" placeholder="Anything here..." auto-focus bindinput="inputChangeHandle" bindchange="addTodoHandle"/>
As input in the above code.
II. Life cycle function
// ===== Page Life Cycle Approach===== onLoad: function () { // Get task list data from the cache and set it with setData var todos = wx.getStorageSync('todo_list') // Call the WX API to retrieve data from the local cache if (todos) { var leftCount = todos.filter(function (item) { return !item.completed }).length this.setData({ todos: todos, leftCount: leftCount }) } // Setting logs data var logs = wx.getStorageSync('todo_logs') if (logs) { this.setData({ logs: logs }) } },
-
onLoad: Page loading
A page can only be called once. Receiving page parameters can obtain query in wx.navigateTo and wx.redirectTo and <navigator/>.
setData: Accepts an object and changes the value of the key in this.data to value in the form of key and value.
3. Event Handling Function
New task handler:
addTodoHandle: function (e) { if (!this.data.input || !this.data.input.trim()) return this.setData( { addOneLoading: true }); //open loading this.setData( { loadingHidden: false, loadingText: 'Waiting...' }); var todos = this.data.todos todos.push({ name: this.data.input, completed: false }) var logs = this.data.logs logs.push({ timestamp: new Date().toLocaleString(), action: 'Newly added', name: this.data.input }) this.setData({ input: '', todos: todos, leftCount: this.data.leftCount + 1, logs: logs }) this.save() }, save: function () { wx.setStorageSync('todo_list', this.data.todos) wx.setStorageSync('todo_logs', this.data.logs) //close loading and toggle button loading status var self = this; setTimeout( function() { self.setData( { loadingHidden: true, addOneLoading: false, loadingText: '' }); }, 100); },
push the three fields of time new Date().toLocaleString(), action:'new', event name: this.data.input into the data data of todos, and then set the cache in save() by wx.setStorageSync('todo_list', this.data.todos).
Task Item Click State Switching Function:
toggleTodoHandle: function (e) { var index = e.currentTarget.dataset.index var todos = this.data.todos todos[index].completed = !todos[index].completed var logs = this.data.logs logs.push({ timestamp: new Date().toLocaleString(), action: todos[index].completed ? 'Mark completion' : 'Markup not completed', name: todos[index].name }) this.setData({ todos: todos, leftCount: this.data.leftCount + (todos[index].completed ? -1 : 1), logs: logs }) this.save() },
var index = e.currentTarget.dataset.index gets the current index, and the corresponding wxml code is:
<view class="item{{ item.completed ? ' completed' : '' }}" wx:for="{{ todos }}" wx:key="{{ index }}" bindtap="toggleTodoHandle" data-index="{{ index }}"> <!-- completed: success, todo: circle --> <icon class="checkbox" type="{{ item.completed ? 'success' : 'circle' }}"/> <text class="name">{{ item.name }}</text> <icon class="remove" type="clear" size="16" catchtap="removeTodoHandle" data-index="{{ index }}"/> </view>
bindtap: When the user clicks on the component, the corresponding event handler will be found in the corresponding Page of the page.
Finally, considering the effect of loading, we need to use the loading attribute of button component to achieve. But loading is just a style control, it doesn't control whether the button can be clicked repeatedly. So we also need to use the disabled attribute of button to prevent repeated clicks.
<button type="primary" size="mini" bindtap="addTodoHandle" loading="{{addOneLoading}}" disabled="{{addOneLoading}}"> + Add </button>
js:
loadingChange: function() { this.setData({ loadingHidden: true, loadingText: '' }); }, toastChange: function() { this.setData( { toastHidden: true, toastText: '' }); }
The LOGS page is relatively simple, mainly through var logs = wx.getStorageSync('todo_logs')
Get a list of logs, and then render the page. There's no code to paste here.
So far, we have a basic understanding of the construction process of TODOS application. We have learned the view layer description language WXML and WXSS developed by Wechat itself and the logical layer framework based on JavaScript through code details and referring to official documents of Wechat applet. It is similar to HTML, so it is easy to learn. However, only through this TODOS application, it is only to understand some basic usage of the small program platform. Complexity, page jumps, network requests and so on need us to practice, in order to understand more about small programs.
Complete code:
source code
Reference material:
1.https://github.com/zce/weapp-...
2.http://www.cnblogs.com/lyzg/p...