Home > WeChat Applet > Mini Program Development > WeChat mini program development (1) Detailed explanation of transforming service account into mini program example

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example

零下一度
Release: 2017-05-23 13:12:22
Original
3286 people have browsed it

WeChat application account (mini program, the new name of "application account") is finally here!

It is still in the internal testing stage, and WeChat has only invited some companies to participate in the closed beta test. Everyone must be concerned about what the final form of the application account will look like? How to transform a "service account" into a "mini program"?

Let’s temporarily demonstrate the development process with an example of a simple third-party tool. (The company's project is confidential and cannot share codes and screenshots. Boka Jun secretly wrote tutorials for everyone while working overtime. Thanks to the "Business Card Box" team for providing their service number to perform this surgery, so Boka Jun's tutorial uses " The public account of "Business Card Box" will be released on a rolling basis?)

OK, in order for everyone to see this tutorial as soon as possible, Mr. Boka is destined to stay up late! I'll start updating tonight, and I hope to post the first tutorial early tomorrow morning! Recording begins! Let’s see how many days it takes to complete the transformation!

Preface

Before you start developing an application account, let’s take a look at the official “Mini Program” tutorial! (The following content comes from the "Mini Program" development guide officially announced by WeChat)

This document will take you step by step to create a WeChat mini program, and you can experience the actual effect of the mini program on your mobile phone. The home page of this mini program will display the welcome message and the current user's WeChat avatar. Click on the avatar to view the startup log of the current mini program in the newly opened page.

1. Get the AppID of the WeChat applet

First of all, we need to have an account. If you can see the document, we should have invited and created it for you What an account. Note that the AppID of the service account or subscription account cannot be used directly. Use the provided account to log in to mp.weixin.qq.com, and you can view the AppID of the WeChat applet in the website's "Settings" - "Developer Settings".

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


Note: If we do not use the administrator WeChat account bound during registration, try the mini program on your mobile phone . Then we still need to operate "Bind Developer". That is, in the "User Identity - Developer" module, bind the WeChat ID you need to experience the mini program. By default, this tutorial uses the administrator's WeChat ID to register an account and experience.

2. Create a project

We need to use developer tools to complete mini program creation and code editing.

After the developer tools are installed, open and use WeChat to scan the QR code to log in. Select Create "Project", fill in the AppID obtained above, set a local project name (not a mini program name), such as "My First Project", and select a local folder as the directory where the code is stored , just click "New Project".

In order to facilitate beginners to understand the basic code structure of the WeChat applet, during the creation process, if the selected local folder is an empty folder, the developer tool will prompt whether it is necessary to create a quick start project. Select "Yes", the developer tools will help us generate a simple demo in the development directory.

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


After the project is successfully created, we can click on the project to enter and see the complete developer tool interface. Click on the left navigation, you can view and edit our code in "Edit", you can test the code and simulate the effect of the mini program on the WeChat client in "Debugging", and you can send it to "Project" Preview the actual effect on your mobile phone.

3. Write code

Click "Edit" in the left navigation of the developer tools. We can see that this project has been initialized and contains some simple code. document. The most critical and essential ones are app.js, app.json, and app.wxss. Among them, the .js suffix is ​​a script file, the .json suffix is ​​a configuration file, and the .wxss suffix is ​​a style sheet file. The WeChat applet will read these files and generate applet instances.

Let’s briefly understand the functions of these three files to facilitate modification and develop your own WeChat applet from scratch.

app.js is the script code of the mini program. We can monitor and process the life cycle functions of the applet and declare global variables in this file. Call the rich API provided by MINA, such as synchronous storage and synchronous reading of local data in this example.

//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}})
Copy after login

app.json is the global configuration of the entire applet. In this file, we can configure which pages the mini program consists of, configure the window background color of the mini program, configure the navigation bar style, and configure the default title. Note that no comments can be added to this file.

{"pages":["pages/index/index","pages/logs/logs"],"window":{"backgroundTextStyle":"light","navigationBarBackgroundColor": "#fff","navigationBarTitleText": "WeChat","navigationBarTextStyle":"black"}}
app.wxss 是整个小程序的公共样式表。我们可以在页面组件的 class 属性上直接使用 app.wxss 中声明的样式规则。
/**app.wxss**/.container {height: 100%;display: flex;flex-direction: column;align-items: center;justify-content: space-between;padding: 200rpx 0;box-sizing: border-box;}
###
Copy after login

4. Create a page

In this tutorial, we have two pages, the index page and the logs page, namely the welcome page and the display page of the applet startup log. They All in the pages directory. The [path + page name] of each page in the WeChat mini program needs to be written in pages of app.json, and the first page in pages is the homepage of the mini program.

每一个小程序页面是由同路径下同名的四个不同后缀文件的组成,如:index.js、index.wxml、index.wxss、index.json。.js 后缀的文件是脚本文件,.json 后缀的文件是配置文件,.wxss 后缀的是样式表文件,.wxml 后缀的文件是页面结构文件。

index.wxml 是页面的结构文件:"

{{userInfo.nickName}}
{{motto}}
Copy after login

"本例中使用了 、、 来搭建页面结构,绑定数据和交互处理函数。

index.js 是页面的脚本文件,在这个文件中我们可以监听并处理页面的生命周期函数、获取小程序实例,声明并处理数据,响应页面交互事件等。//index.js// 获取应用实例

var app = getApp()Page({data: {motto: 'Hello World',userInfo: {}},// 事件处理函数bindViewTap: function() {wx.navigateTo({url: '../logs/logs'})},onLoad: function () {console.log('onLoad')var that = this// 调用应用实例的方法获取全局数据app.getUserInfo(function(userInfo){// 更新数据that.setData({userInfo:userInfo})})}})
Copy after login

index.wxss 是页面的样式表:

"/index.wxss/.userinfo {display: flex;flex-direction: column;align-items: center;}
.userinfo-avatar {width: 128rpx;height: 128rpx;margin: 20rpx;border-radius: 50%;}
.userinfo-nickname {color: #aaa;}
.usermotto {margin-top: 200px;}"
Copy after login

页面的样式表是非必要的。当有页面样式表时,页面的样式表中的样式规则会层叠覆盖 app.wxss 中的样式规则。如果不指定页面的样式表,也可以在页面的结构文件中直接使用 app.wxss 中指定的样式规则。

index.json 是页面的配置文件:

页面的配置文件是非必要的。当有页面的配置文件时,配置项在该页面会覆盖 app.json 的 window 中相同的配置项。如果没有指定的页面配置文件,则在该页面直接使用 app.json 中的默认配置。

logs 的页面结构

{{index + 1}}. {{log}}
Copy after login

logs 页面使用 控制标签来组织代码,在 上使用 wx:for-items 绑定 logs 数据,并将 logs 数据循环展开节点

//logs.jsvar util = require('../../utils/util.js')Page({data: {logs: []},onLoad: function () {this.setData({logs: (wx.getStorageSync('logs') || []).map(function (log) {return util.formatTime(new Date(log))})})}})
Copy after login

运行结果如下:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example

5. 手机预览

开发者工具左侧菜单栏选择「项目」,点击「预览」,扫码后即可在微信客户端中体验。

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


目前,预览和上传功能尚无法实现,需要等待微信官方的下一步更新。

如你所见,微信官方给出的开发指南还非常简单,很多细节、代码和功能都没有明确的展示,所以接下来就到展示实力的时候啦!开发教程正式开始!

第一章:准备工作

做好准备工作很重要。开发一个微信应用号,你需要提前到微信的官方网站(weixin.qq.com)下载开发者工具。

  • 下载最新微信开发者工具,打开后你会看到该界面:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


  • 点击「新建 web+」项目,随后出现如下画面:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


  • 该页面内的各项内容需要注意——

  • AppID:依照官方解释来填。 Appname: 项目最外层文件夹名称,如你将其命名为「ABC」,则之后的全部项目内容均将保存在「/ABC/…」目录下。 本地开发目录:项目存放在本地的目录。

注:再次强调,如果你和团队成员共同开发该项目,则建议你们使用同样的目录名称及本地目录,以确保协同开发的统一性。如果你之前已有项目,则导入过程与以上内容近似,不再赘述。

  • 准备工作全部完成后,点击「新建项目」按钮,弹出框点「确定」。

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


  • 如上图所示,此刻,微信开发者工具已经为你自动构建了一个初始的 demo 项目,该项目内包含了一个微信应用项目所需具备的基本内容和框架结构。点击项目名称(图中即「cards」)进入该项目,就能看到整个项目的基本架构了:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


第二章:项目构架

WeChat currently has a very large user base. After WeChat launched the official account, everyone can see the popularity, which also promotes the rapid development of h5. As the needs of the official account business become more and more complex, the arrival of the application account is also Just right. After reading the document once or twice, our team found that the way it provides developers is also undergoing comprehensive changes, from operating DOM to operating data. It is difficult to implement many h5 based on a bridge tool provided by WeChat on public accounts. The implemented functions are somewhat similar to hybrid development. The difference from hybrid development is that WeChat’s open interface is more rigorous, and the structure must adopt the components it provides us. External frameworks and plug-ins cannot be used here, allowing developers to Developers are completely separated from operating DOM, and their development thinking has changed greatly.

If a worker wants to do his job well, he must first sharpen his tools. It is very important to understand its core functions and first understand its entire operation process.

Life cycle:

In index.js:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


##Developer In the console on the tool, you can see:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


In the console on the home page, you can see that the order is App Launch-->App Show -->onload-->onShow-->onReady.

The first is the startup and display of the entire app. The startup of the app can be configured in app.js, and then it goes to the loading and display of each page, etc.

As you can imagine, a lot of things can be processed here, such as loading boxes and so on.

Routing:

Routing has always been a core point in project development. In fact, WeChat has very little introduction to routing here. It can be seen that WeChat is The routing is well encapsulated and three jump methods are provided.

These three are basically sufficient. WeChat is well packaged in terms of routing. Developers do not need to configure routing at all. Many frameworks often have very cumbersome routing configuration.

Components:

This time WeChat is also very comprehensive in terms of component provision, which basically meets the project needs, so the development speed is very fast. You can browse it carefully several times before development. , the development efficiency will be very good.

Others:

Any external frameworks and plug-ins are basically unusable, even native js plug-ins are difficult to use, because in the past our js plug-ins were basically all It exists in the form of operating dom, and the structure of the WeChat application account this time does not allow the operation of any dom. Even the dynamically set rem.js we are used to using is not supported.

This time WeChat also provides WebSocket, which can be used directly for chatting. There is a lot of room for development.

Compared with public accounts, we found that developing application accounts is component-based, structured, and diversified. The New World is always full of surprises, and more Easter eggs are waiting for everyone to discover.

Let’s start with some simple code!

  • Find the project folder and import it into your editor. Here, I used the Sublime Text editor. You can choose your favorite editor based on your development habits.

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


    ##Next, you need to adjust it according to the content of your project Project structure. In the sample project, the "card_course" directory mainly contains the "tabBar" page and some configuration files of the application.
  • The "tabBar" of the example project is five menu buttons:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


##Find the "app.json" file to configure these five menus. Find "tabBar" in the line of code:

WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


## You can Change according to actual project requirements, including:

  • "Color" is the bottom font color, "selectedColor" is the highlight color when switching to the page, "borderStyle" is the color of the line above the switching menu, "backgroundColor" is the bottom menu bar background color. The text description is relatively abstract. It is recommended that you debug it one by one and check its effects to deepen your impression. The order of codes under ""list"" must be placed in order and cannot be changed casually. In the file name after ""pagePath"", the ".wxml" suffix is ​​hidden. This is a humane aspect of WeChat development code - it helps you save time in writing code and does not need to frequently declare file suffixes. ""iconPath"" is the icon path of the page that has not been displayed. These two paths can be directly network icons. ""selectedIconPath"" is the path of the highlighted icon on the currently displayed page. It can be removed. After removal, the icon will be displayed as ""iconPath"" by default. * ""Text"" is the page title, which can also be removed. After removing it, the icon will be displayed only. If only one of them is removed, the position will be occupied.

  • Note: WeChat’s bottom menu supports up to five columns (five icons), so when you design the UI and basic structure of your WeChat application, you must consider the layout of the menu bar in advance. .

    • According to the above code rules, I have prepared the basic structure of the sample project for your reference:

    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


    Note: I personally recommend that when you create a new "wxml" file, you also create the corresponding "js" and "wxss" files together, because the configuration characteristics of the WeChat application account are When a "wxml" file is parsed, "js" and "wxss" files with the same file name will be found in the same directory at the same time, so the "js" file must be pre-configured in "app.json" in time.

    When writing "wxml", just code according to the interface provided by the WeChat application account. Most of them are the previous "p", but we now use "view". When you need to use other subsets, you can choose according to the interface provided by WeChat.

    Use the "class" name to set the style. The "id" name is basically useless here. Mainly operates data, not "dom".

    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


    • The above is the "wxml" encoding for the sample project homepage. As can be seen from the picture, the amount of code to implement a page is very small.

    • The "Wxss" file is an imported style file. You can also write styles directly in it. The example uses the import method:

    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


    • Revise After refreshing the code, you can see that the "view" label without a background directly turns pink.

    Note: After modifying the content under "wxml" and "wxss", you can directly refresh with F5 to see the effect. If you modify "js", you need to click the restart button to see the effect. .

    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


      ##The "Js" file needs to be in "app.json" It is pre-configured in the ""page"" of the file. In order to clarify the project structure, I created four other page files in the directory at the same level as the "index" homepage in the sample project, as follows:

    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example


    WeChat mini program development (1) Detailed explanation of transforming service account into mini program example
    After the above steps, the five bottom menus in the case are all configured.


    【related suggestion】

    1. Complete source code download of WeChat mini program

    2. WeChat mini program game demo to select different color blocks

    3. WeChat applet demo: Guoku updated version

    The above is the detailed content of WeChat mini program development (1) Detailed explanation of transforming service account into mini program example. For more information, please follow other related articles on the PHP Chinese website!

    source:php.cn
    Statement of this Website
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template