一、开始微信小程序
有人问我微信小程序的开发需要学什么,有什么视频啥的。想起来我刚接触微信小程序的时候,也是十分的迷茫,用了很长的时间研究如下的问题。下面的介绍是我学习了 vue
之后,再次学习微信小程序时写的,相比较来说,比之前更加规范了,理解也更深刻。
1、数据交互
现在的开发都想要前后端分离,那么微信小程序作为前端,如何与后端(例如 SpringBoot 开发的后端)进行数据的交互。
- 微信小程序 通过API
wx.request
发起网络请求,SpringBoot
作为后端提供请求url,例如http:localhost:8080/emp
的GET
请求。 - 交互的数据格式使用
json
(json的处理库有:Gson,FastJson,Jackson,Json-lib),其中Gson是Google的产品,FastJson是alibaba的产品 也是我比较喜欢的产品。 - 网络请求的方法包括
GET、POST、PUT、DELETE等
,具体可以学restful风格的API
wx.request({
url: 'http:localhost:8080/emp',
...
success: function (res) {
//接口调用成功的回调函数
console.log(res);
},
fail: function (res) {
//接口调用失败的回调函数
console.log(res);
},
complete: function (res) {
//接口调用结束的回调函数
console.log(res);
},
})
2、项目结构
如果你学过 vue
,对于 微信小程序
的开发会轻松很多。
项目结构如下:
├── app.js
├── app.json
├── app.wxml
├── app.wxss
├── project.config.json
├── assets
│ └── images #项目中需要用到的静态图片
├── common
│ └── commonUtil.js #项目中用到的工具方法
├── components #项目中需要用到的公共组件
│ └── ...
└── network
├── request.js # 对数据请求的封装
├── config.js # 网络请求的配置,如baseurl、timeout等
├── home.js # home页面中用到的网络请求
├── ...
└── pages
├── home # home页面的内容
├── home.js
├── home.json
├── home.wxml
├── home.wxss
├── childCpns #home中用到的组件
├── ...
二、例子
1、后端
@RestController
public class EmpController {
@GetMapping("/emp")
public JSONObject hello() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","zhangsan");
jsonObject.put("age","23");
jsonObject.put("mobile","155*****795");
return jsonObject;
}
}
浏览器中输入 http://localhost:8080/emp
,出现如下结果时,说明后端可以了。
2、前端
下面的内容用到了 JavaScript
中的 promise
知识,如果不知道,需要自学。
//network/config.js
export const baseURL = 'http://localhost:8080'
export const timeout = 5000
//network/request.js
import {baseURL, timeout} from './config.js'
//网络请求方法
export default function request(options) {
wx.showLoading({
title: '数据加载中ing',
})
//返回Promise对象
return new Promise((resolve, reject) => {
wx.request({
url: baseURL + options.url,
timeout: timeout,
data: options.data,
success: function (res) {
resolve(res.data) //成功时调用
},
fail: reject, //失败时调用
complete: res => {
wx.hideLoading()
}
})
})
}
//network/home.js
import request from './request.js'
//GET请求emp
export function getEmp() {
return request({
url: '/emp',
method: 'GET'
})
}
//pages/home/home.js
import {
//...
getEmp
} from '../../network/home.js'
Page({
/**
* 页面的初始数据
*/
data: {
emps: []
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const that = this;
//网络获取数据
that._getData();
},
//网络请求数据
_getData() {
const that = this;
that._getMultiData();
},
//请求emp
_getEmp(){
const that = this;
getEmp()
.then(res => {
//网络请求成功,在其中数据绑定、数据处理等
console.log(res);
})
.catch(res => {
//网络请求失败
console.log(res);
})
}
//请求其他数据
//...
})