微信小程序

深碍√TFBOYSˉ_ 2022-02-23 13:37 774阅读 0赞

1.安装微信开发者工具

window 64:
https://servicewechat.com/wxa…
window 32:
https://servicewechat.com/wxa…
mac:
https://servicewechat.com/wxa…

2.创建新项目

开发者工具安装完成后,打开并使用微信扫码登录。选择添加“项目”,填入AppID,如果没有,选择无AppleID,命名”myWeChat”,并选择一个本地的文件夹作为代码存储的目录,点击“添加项目”,此时开发者工具会提示,是否需要创建一个 quick start 项目。选择“是”,开发者工具会帮助我们在开发目录里生成一个简单的 demo。

3.编写代码

点击开发者工具左侧导航的“编辑”,可以看到这个项目,已经初始化并包含了一些简单的代码文件。最关键也是必不可少的,是 app.js、app.json、app.wxss 这三个。其中,.js后缀的是脚本文件,.json后缀的文件是配置文件,.wxss后缀的是样式表文件。微信小程序会读取这些文件,并生成小程序实例。
app.js是小程序的脚本代码。我们可以在这个文件中监听并处理小程序的生命周期函数、声明全局变量。调用框架提供的丰富的 API,如本例的同步存储及同步读取本地数据。

app.js:

  1. App({
  2. onLaunch: function () {
  3. console.log('App Launch');
  4. //调用API从本地缓存中获取数据
  5. var logs = wx.getStorageSync('logs') || []
  6. logs.unshift(Date.now())
  7. wx.setStorageSync('logs', logs)
  8. },
  9. onShow: function () {
  10. console.log('App Show')
  11. },
  12. onHide: function () {
  13. console.log('App Hide')
  14. },
  15. getUserInfo:function(cb){
  16. var that = this
  17. if(this.globalData.userInfo){
  18. typeof cb == "function" && cb(this.globalData.userInfo)
  19. }else{
  20. //调用登录接口
  21. wx.login({
  22. success: function () {
  23. wx.getUserInfo({
  24. success: function (res) {
  25. that.globalData.userInfo = res.userInfo
  26. typeof cb == "function" && cb(that.globalData.userInfo)
  27. }
  28. })
  29. }
  30. })
  31. }
  32. },
  33. globalData:{
  34. userInfo:null,
  35. currData: 'I am is global data'
  36. }
  37. })

app.json 是对整个小程序的全局配置。我们可以在这个文件中配置小程序是由哪些页面组成,配置小程序的窗口背景色,配置导航条样式,配置默认标题。注意该文件不可添加任何注释。

app.json:

  1. {
  2. "pages":[
  3. "pages/index/index",
  4. "pages/logs/logs",
  5. "pages/newPage/newPage"
  6. ],
  7. "window":{
  8. "backgroundColor": "#49CB5F",
  9. "backgroundTextStyle":"dark",
  10. "navigationBarBackgroundColor": "#F8DBF8",
  11. "navigationBarTitleText": "xhh",
  12. "navigationBarTextStyle": "black",
  13. "enablePullDownRefresh": true
  14. },
  15. "tabBar": {
  16. "color": "#B91ABB",
  17. "selectedColor": "#A349A4",
  18. "backgroundColor": "#F8DBF8",
  19. "borderStyle": "white",
  20. "list": [{
  21. "pagePath": "pages/index/index",
  22. "iconPath": "image/icon_component.png",
  23. "selectedIconPath": "image/icon_component_HL.png",
  24. "text": "首页"
  25. }, {
  26. "pagePath": "pages/logs/logs",
  27. "iconPath": "image/icon_API.png",
  28. "selectedIconPath": "image/icon_API_HL.png",
  29. "text": "日志"
  30. },{
  31. "pagePath": "pages/newPage/newPage",
  32. "iconPath": "image/wechat.png",
  33. "selectedIconPath": "image/wechatHL.png",
  34. "text": "其他"
  35. }]
  36. },
  37. "networkTimeout": {
  38. "request": 10000,
  39. "downloadFile": 10000,
  40. "uploadFile": 10000,
  41. "connectSocket": 10000
  42. },
  43. "debug": false
  44. }

app.wxss 是整个小程序的公共样式表。我们可以在页面组件的 class 属性上直接使用app.wxss 中声明的样式规则。

app.wxss:

  1. .container {
  2. height: 100%;
  3. display: flex;
  4. flex-direction: column;
  5. align-items: center;
  6. justify-content: space-between;
  7. /*padding: 200rpx 0;*/
  8. padding-top: 200rpx;
  9. box-sizing: border-box;
  10. }

4.创建页面

index 页面,logs 页面和newPage 页面都在 pages 目录下。微信小程序中的每一个页面的【路径+页面名】都需要写在 app.json 的 pages 中,且 pages 中的第一个页面是小程序的首页。
每一个小程序页面是由同路径下同名的四个不同后缀文件的组成,如:index.js、index.wxml、index.wxss、index.json。.js后缀的文件是脚本文件,.json后缀的文件是配置文件,.wxss后缀的是样式表文件,.wxml后缀的文件是页面结构文件。

index 页面结构如下。

index.wxml:

  1. <view class="container">
  2. <view bindtap="bindViewTap" class="userinfo">
  3. <image class="userinfo-avatar" src="{
  4. {userInfo.avatarUrl}}" background-size="cover"></image>
  5. <text class="userinfo-nickname">{
  6. {userInfo.nickName}}</text>
  7. </view>
  8. <view class="usermotto">
  9. <text class="user-motto">{
  10. {motto}}</text>
  11. </view>
  12. <view class="copyright">{
  13. {array[0].msg}}</view>
  14. </view>

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

index.js:

  1. //获取应用实例
  2. var app = getApp();
  3. console.log(app.globalData.currData);
  4. Page({
  5. data: {
  6. motto: 'Hello xhh',
  7. userInfo: {},
  8. array: [{msg: '版权所有,翻版必究'}, {msg: 'msg2'}]
  9. },
  10. //事件处理函数
  11. bindViewTap: function() {
  12. wx.navigateTo({
  13. url: '../logs/logs'
  14. })
  15. },
  16. onLoad: function () {
  17. console.log('onLoad')
  18. var that = this
  19. //调用应用实例的方法获取全局数据
  20. app.getUserInfo(function(userInfo){
  21. //更新数据
  22. that.setData({
  23. userInfo:userInfo
  24. })
  25. })
  26. },
  27. onReady: function () {
  28. console.log('onReady');
  29. },
  30. onShow: function () {
  31. console.log('onShow');
  32. },
  33. onHide: function () {
  34. console.log('onHide');
  35. },
  36. onUnload: function () {
  37. console.log('onUnload');
  38. }
  39. })

index.wxss:

  1. .userinfo {
  2. display: flex;
  3. flex-direction: column;
  4. align-items: center;
  5. }
  6. .userinfo-avatar {
  7. width: 128rpx;
  8. height: 128rpx;
  9. margin: 20rpx;
  10. border-radius: 50%;
  11. }
  12. .userinfo-nickname {
  13. color: #aaa;
  14. }
  15. .usermotto {
  16. margin-top: 200px;
  17. }
  18. .copyright {
  19. text-align:center;
  20. font-size:0.8rem;
  21. color: blueviolet;
  22. margin-top: 120rpx;
  23. }

页面的样式表是非必要的。当有页面样式表时,页面的样式表中的样式规则会层叠覆盖 app.wxss 中的样式规则。如果不指定页面的样式表,也可以在页面的结构文件中直接使用 app.wxss 中指定的样式规则。
index.json 是页面的配置文件:
页面的配置文件是非必要的。当有页面的配置文件时,配置项在该页面会覆盖 app.json 的 window 中相同的配置项。如果没有指定的页面配置文件,则在该页面直接使用 app.json 中的默认配置。

index.json:

  1. {
  2. "backgroundColor":"#49CB5F"
  3. }

logs 页面结构如下。

logs.wxml:

  1. <view class="container log-list">
  2. <block wx:for="{
  3. {logs}}" wx:for-item="log" wx:key="*this">
  4. <text class="log-item">{
  5. {index + 1}}. {
  6. {log}}</text>
  7. </block>
  8. </view>

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

logs.js:

  1. var util = require('../../utils/util.js');
  2. var common = require('../../utils/common.js');
  3. Page({
  4. data: {
  5. logs: [],
  6. },
  7. onLoad: function () {
  8. this.setData({
  9. logs: (wx.getStorageSync('logs') || []).map(function (log) {
  10. return util.formatTime(new Date(log))
  11. })
  12. })
  13. },
  14. onShow: function () {
  15. common.sayHello('xhh')
  16. },
  17. onShareAppMessage: function () {
  18. return {
  19. title: '自定义分享标题',
  20. desc: '自定义分享描述',
  21. path: '/page/user?id=123'
  22. }
  23. }
  24. })

logs.wxss:

  1. .log-list {
  2. display: flex;
  3. flex-direction: column;
  4. padding: 40rpx;
  5. }
  6. .log-item {
  7. margin: 10rpx;
  8. }

logs.json:

  1. {
  2. "navigationBarTitleText": "查看启动日志"
  3. }

newPage 页面结构如下。

newPage.wxml:

  1. <block wx:for-items="{
  2. {arrayList}}">
  3. <text> {
  4. {index}}: </text>
  5. <text> {
  6. {item}} </text>
  7. <view></view>
  8. </block>
  9. <view wx:if="{
  10. {view == 'WEBVIEW'}}"> WEBVIEW </view>
  11. <view wx:elif="{
  12. {view == 'APP'}}"> APP </view>
  13. <view wx:else="{
  14. {view == 'view'}}"> VIEW </view>
  15. <template name="staffName">
  16. <view>
  17. FirstName: {
  18. {firstName}}, LastName: {
  19. {lastName}}
  20. </view>
  21. </template>
  22. <template is="staffName" data="{
  23. {...staffA}}"></template>
  24. <template is="staffName" data="{
  25. {...staffB}}"></template>
  26. <template is="staffName" data="{
  27. {...staffC}}"></template>
  28. <view bindtap="add"> 点我计数:{
  29. {count}} </view>
  30. <button bindtap="changeName"> Click me! Change the data below </button>
  31. <view style="margin-top:10rpx">{
  32. {obj.text}}</view>
  33. <view class="section">
  34. <view class="section__title">日期选择器:</view>
  35. <picker mode="date" value="{
  36. {date}}" start="2015-09-01" end="2018-01-01" bindchange="bindDateChange">
  37. <view class="picker">
  38. <label>当前选择:</label>
  39. <input class="dateInput" value="{
  40. {date}}" />
  41. </view>
  42. </picker>
  43. </view>
  44. <view class="group">
  45. <block wx:for="{
  46. {iconSize}}">
  47. <icon type="success" size="{
  48. {item}}" />
  49. </block>
  50. </view>
  51. <view class="group">
  52. <block wx:for="{
  53. {iconType}}">
  54. <icon type="{
  55. {item}}" size="45" />
  56. </block>
  57. </view>
  58. <view class="group">
  59. <block wx:for="{
  60. {iconColor}}">
  61. <icon type="success" size="45" color="{
  62. {item}}" />
  63. </block>
  64. </view>
  65. <swiper indicator-dots="{
  66. {indicatorDots}}" autoplay="{
  67. {autoplay}}" interval="{
  68. {interval}}" duration="{
  69. {duration}}" current="{
  70. {currentPage}}">
  71. <block wx:for-items="{
  72. {imgUrls}}">
  73. <swiper-item>
  74. <image src="{
  75. {item}}" class="slide-image" width="355" height="150" />
  76. </swiper-item>
  77. </block>
  78. </swiper>
  79. <button bindtap="changeIndicatorDots" class="btnStyle"> indicator-dots </button>
  80. <button bindtap="changeAutoplay" class="btnStyle"> autoplay </button>
  81. <button bindtap="nextPage" class="btnStyle"> next page </button>
  82. <slider bindchange="intervalChange" show-value min="500" max="2000" /> interval
  83. <slider bindchange="durationChange" show-value min="1000" max="10000" /> duration
  84. <audio poster="{
  85. {poster}}" name="{
  86. {name}}" author="{
  87. {author}}" src="{
  88. {src}}" id="myAudio" controls loop></audio>
  89. <button type="primary" class="btnStyle" bindtap="audioPlay">播放</button>
  90. <button type="primary" class="btnStyle" bindtap="audioPause">暂停</button>
  91. <button type="primary" class="btnStyle" bindtap="audio14">设置当前播放时间为14秒</button>
  92. <button type="primary" class="btnStyle" bindtap="audioStart">回到开头</button>
  93. <button type="primary" class="btnStyle" bindtap="makeCall">拨打电话</button>
  94. <button type="primary" class="btnStyle" bindtap="sendAjax">发送请求</button>
  95. <button type="primary" class="btnStyle" bindtap="checkMap">查看位置</button>
  96. <canvas style="width: 300px; height: 200px;" canvas-id="firstCanvas"></canvas>

newPage.js:

  1. Page({
  2. onReady: function (e) {
  3. // 使用 wx.createAudioContext 获取 audio 上下文 context
  4. this.audioCtx = wx.createAudioContext('myAudio');
  5. wx.showToast({
  6. title: '成功',
  7. icon: 'success',
  8. duration: 2000
  9. })
  10. // 使用 wx.createContext 获取绘图上下文 context
  11. var context = wx.createContext()
  12. context.setStrokeStyle("#00ff00")
  13. context.setLineWidth(5)
  14. context.rect(0, 0, 200, 200)
  15. context.stroke()
  16. context.setStrokeStyle("#ff0000")
  17. context.setLineWidth(2)
  18. context.moveTo(160, 100)
  19. context.arc(100, 100, 60, 0, 2 * Math.PI, true)
  20. context.moveTo(140, 100)
  21. context.arc(100, 100, 40, 0, Math.PI, false)
  22. context.moveTo(85, 80)
  23. context.arc(80, 80, 5, 0, 2 * Math.PI, true)
  24. context.moveTo(125, 80)
  25. context.arc(120, 80, 5, 0, 2 * Math.PI, true)
  26. context.stroke()
  27. // 调用 wx.drawCanvas,通过 canvasId 指定在哪张画布上绘制,通过 actions 指定绘制行为
  28. wx.drawCanvas({
  29. canvasId: 'firstCanvas',
  30. actions: context.getActions() // 获取绘图动作数组
  31. })
  32. },
  33. data: {
  34. arrayList: ['item1', 'item2', 'item3', 'item4', 'item5'],
  35. view: 'WEBVIEW',
  36. staffA: { firstName: 'Hulk', lastName: 'Hu' },
  37. staffB: { firstName: 'Shang', lastName: 'You' },
  38. staffC: { firstName: 'Gideon', lastName: 'Lin' },
  39. count: 1,
  40. obj: { text: 'data' },
  41. iconSize: [20, 30, 40, 50, 60, 70],
  42. iconColor: [
  43. 'red', 'orange', 'yellow', 'green', 'rgb(0,255,255)', 'blue', 'purple'
  44. ],
  45. iconType: [
  46. 'success', 'info', 'warn', 'waiting', 'safe_success', 'safe_warn',
  47. 'success_circle', 'success_no_circle', 'waiting_circle', 'circle', 'download',
  48. 'info_circle', 'cancel', 'search', 'clear'
  49. ],
  50. imgUrls: [
  51. 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
  52. 'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
  53. 'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
  54. ],
  55. indicatorDots: false,
  56. autoplay: false,
  57. interval: 5000, // 自动切换时间间隔
  58. duration: 1000, // 滑动动画时长
  59. currentPage: 1,
  60. poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
  61. name: '此时此刻',
  62. author: '许巍',
  63. src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
  64. },
  65. changeName: function (e) {
  66. if (this.data.obj.text == "data") {
  67. this.setData({
  68. obj: { text: 'changed data' }
  69. })
  70. } else {
  71. this.setData({
  72. obj: { text: 'data' }
  73. })
  74. }
  75. console.log(this.data.obj.text);
  76. },
  77. add: function (e) {
  78. this.setData({
  79. count: this.data.count + 1
  80. })
  81. },
  82. bindDateChange: function (e) {
  83. this.setData({
  84. date: e.detail.value
  85. })
  86. console.log(this.data.date);
  87. },
  88. changeIndicatorDots: function (e) {
  89. this.setData({
  90. indicatorDots: !this.data.indicatorDots
  91. })
  92. },
  93. changeAutoplay: function (e) {
  94. this.setData({
  95. autoplay: !this.data.autoplay
  96. })
  97. },
  98. intervalChange: function (e) {
  99. this.setData({
  100. interval: e.detail.value
  101. })
  102. },
  103. durationChange: function (e) {
  104. this.setData({
  105. duration: e.detail.value
  106. })
  107. },
  108. nextPage: function (e) {
  109. var temp = this.data.currentPage + 1;
  110. if (temp >= 3) {
  111. temp = 0;
  112. }
  113. this.setData({
  114. currentPage: temp
  115. })
  116. },
  117. audioPlay: function () {
  118. this.audioCtx.play()
  119. },
  120. audioPause: function () {
  121. this.audioCtx.pause()
  122. },
  123. audio14: function () {
  124. this.audioCtx.seek(14)
  125. },
  126. audioStart: function () {
  127. this.audioCtx.seek(0)
  128. },
  129. makeCall: function () {
  130. wx.makePhoneCall({
  131. phoneNumber: '15151547384'
  132. })
  133. },
  134. sendAjax: function () {
  135. wx.request({
  136. url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN',
  137. data: {
  138. "path": "pages/index?query=1",
  139. "width": 430
  140. },
  141. header: {
  142. 'content-type': 'application/json'
  143. },
  144. method: 'POST',
  145. success: function (res) {
  146. console.log(res.data);
  147. },
  148. fail: function () {
  149. },
  150. complete: function () {
  151. }
  152. })
  153. },
  154. checkMap: function () {
  155. wx.getLocation({
  156. type: 'gcj02', //返回可以用于wx.openLocation的经纬度
  157. success: function (res) {
  158. var latitude = res.latitude
  159. var longitude = res.longitude
  160. wx.openLocation({
  161. latitude: latitude,
  162. longitude: longitude,
  163. scale: 28
  164. })
  165. }
  166. })
  167. }
  168. })

newPage.wxss:

  1. .dateInput {
  2. display:inline-block;
  3. vertical-align: -8px;
  4. border: 1px solid darkslategray;
  5. }
  6. .section .section__title {
  7. color: blueviolet;
  8. }
  9. .slide-image{
  10. width: 100%;
  11. padding: 40rpx 0;
  12. }
  13. .btnStyle {
  14. width:400rpx;
  15. height:100rpx;
  16. margin-top:40rpx;
  17. margin-bottom: 10rpx;
  18. }

newPage.json:

  1. {
  2. "navigationBarTitleText": "newPage"
  3. }

文件目录结构如下:
图片描述

5.配置

app.json 配置项列表:
图片描述

pages:
接受一个数组,每一项都是字符串,来指定小程序由哪些页面组成。每一项代表对应页面的【路径+文件名】信息,数组的第一项代表小程序的初始页面。小程序中新增/减少页面,都需要对 pages 数组进行修改。
文件名不需要写文件后缀,因为框架会自动去寻找路径.json,.js,.wxml,.wxss的四个文件进行整合。
window:
用于设置小程序的状态栏、导航条、标题、窗口背景色。
图片描述

tabBar:
如果我们的小程序是一个多 tab 应用(客户端窗口的底部或顶部有 tab 栏可以切换页面),那么我们可以通过 tabBar 配置项指定 tab 栏的表现,以及 tab 切换时显示的对应页面。
Tip: 通过页面跳转(wx.navigateTo)或者页面重定向(wx.redirectTo)所到达的页面,即使它是定义在 tabBar 配置中的页面,也不会显示底部的 tab 栏。
tabBar 是一个数组,只能配置最少2个、最多5个 tab,tab 按数组的顺序排序。
图片描述

其中 list 接受一个数组,数组中的每个项都是一个对象,其属性值如下:
图片描述
networkTimeout:
可以设置各种网络请求的超时时间。
图片描述

debug:
可以在开发者工具中开启 debug 模式,在开发者工具的控制台面板,调试信息以 info 的形式给出,其信息有Page的注册,页面路由,数据更新,事件触发 。 可以帮助开发者快速定位一些常见的问题。
page.json:
每一个小程序页面也可以使用.json文件来对本页面的窗口表现进行配置。 页面的配置比app.json全局配置简单得多,只是设置 app.json 中的 window 配置项的内容,页面中配置项会覆盖 app.json 的 window 中相同的配置项。
页面的.json只能设置 window 相关的配置项,以决定本页面的窗口表现,所以无需写 window 这个键。
图片描述

6.逻辑层

(1) 注册程序:
App() 函数用来注册一个小程序。接受一个 object 参数,其指定小程序的生命周期函数等。
object参数说明:
图片描述

前台、后台定义: 当用户点击左上角关闭,或者按了设备 Home 键离开微信,小程序并没有直接销毁,而是进入了后台;当再次进入微信或再次打开小程序,又会从后台进入前台。
只有当小程序进入后台一定时间,或者系统资源占用过高,才会被真正的销毁。
getApp()
我们提供了全局的 getApp() 函数,可以获取到小程序实例。
// other.js

  1. var appInstance = getApp()
  2. console.log(appInstance.globalData) // I am global data

注意:
App() 必须在 app.js 中注册,且不能注册多个。
不要在定义于 App() 内的函数中调用 getApp() ,使用 this 就可以拿到 app 实例。
不要在 onLaunch 的时候调用 getCurrentPage(),此时 page 还没有生成。
通过 getApp() 获取实例之后,不要私自调用生命周期函数。
(2) 注册页面:
Page() 函数用来注册一个页面。接受一个 object 参数,其指定页面的初始数据、生命周期函数、事件处理函数等。
object 参数说明:
图片描述

初始化数据
初始化数据将作为页面的第一次渲染。data 将会以 JSON 的形式由逻辑层传至渲染层,所以其数据必须是可以转成 JSON 的格式:字符串,数字,布尔值,对象,数组。
渲染层可以通过 WXML 对数据进行绑定。
示例代码:

  1. <view>{
  2. {text}}</view>
  3. <view>{
  4. {array[0].msg}}</view>
  5. Page({
  6. data: {
  7. text: 'init data',
  8. array: [{msg: '1'}, {msg: '2'}]
  9. }
  10. })

生命周期函数:

  1. onLoad: 页面加载
  2. 一个页面只会调用一次。
  3. 接收页面参数可以获取wx.navigateTowx.redirectTo及<navigator/>中的 query
  4. onShow: 页面显示
  5. 每次打开页面都会调用一次。
  6. onReady: 页面初次渲染完成
  7. 一个页面只会调用一次,代表页面已经准备妥当,可以和视图层进行交互。
  8. 对界面的设置如wx.setNavigationBarTitle请在onReady之后设置。详见生命周期
  9. onHide: 页面隐藏
  10. navigateTo或底部tab切换时调用。
  11. onUnload: 页面卸载
  12. redirectTonavigateBack的时候调用。
  13. 页面相关事件处理函数
  14. onPullDownRefresh: 下拉刷新
  15. 监听用户下拉刷新事件。
  16. 需要在configwindow选项中开启enablePullDownRefresh
  17. 当处理完数据刷新后,wx.stopPullDownRefresh可以停止当前页面的下拉刷新。
  18. onShareAppMessage: 用户分享
  19. 只有定义了此事件处理函数,右上角菜单才会显示“分享”按钮
  20. 用户点击分享按钮的时候会调用
  21. 此事件需要 return 一个 Object,用于自定义分享内容。

自定义分享字段:
图片描述

示例代码:

  1. Page({
  2. onShareAppMessage: function () {
  3. return {
  4. title: '自定义分享标题',
  5. path: '/page/user?id=123'
  6. }
  7. }
  8. })

事件处理函数
除了初始化数据和生命周期函数,Page 中还可以定义一些特殊的函数:事件处理函数。在渲染层可以在组件中加入事件绑定,当达到触发事件时,就会执行 Page 中定义的事件处理函数。
示例代码:

  1. <view bindtap="viewTap"> click me </view>
  2. Page({
  3. viewTap: function() {
  4. console.log('view tap')
  5. }
  6. })

setData() 参数格式:
接受一个对象,以 key,value 的形式表示将 this.data 中的 key 对应的值改变成 value。
其中 key 可以非常灵活,以数据路径的形式给出,如 array[2].message,a.b.c.d,并且不需要在 this.data 中预先定义。
示例代码:

  1. <!--index.wxml-->
  2. <view>{
  3. {text}}</view>
  4. <button bindtap="changeText"> Change normal data </button>
  5. <view>{
  6. {array[0].text}}</view>
  7. <button bindtap="changeItemInArray"> Change Array data </button>
  8. <view>{
  9. {object.text}}</view>
  10. <button bindtap="changeItemInObject"> Change Object data </button>
  11. <view>{
  12. {newField.text}}</view>
  13. <button bindtap="addNewField"> Add new data </button>
  14. //index.js
  15. Page({
  16. data: {
  17. text: 'init data',
  18. array: [{text: 'init data'}],
  19. object: {
  20. text: 'init data'
  21. }
  22. },
  23. changeText: function() {
  24. // this.data.text = 'changed data' // bad, it can not work
  25. this.setData({
  26. text: 'changed data'
  27. })
  28. },
  29. changeItemInArray: function() {
  30. // you can use this way to modify a danamic data path
  31. this.setData({
  32. 'array[0].text':'changed data'
  33. })
  34. },
  35. changeItemInObject: function(){
  36. this.setData({
  37. 'object.text': 'changed data'
  38. });
  39. },
  40. addNewField: function() {
  41. this.setData({
  42. 'newField.text': 'new data'
  43. })
  44. }
  45. })

(3) 模块化:
模块化
我们可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports 或者 exports 才能对外暴露接口。

需要注意的是:

exports 是 module.exports 的一个引用,因此在模块里边随意更改 exports 的指向会造成未知的错误。所以我们更推荐开发者采用 module.exports 来暴露模块接口,除非你已经清晰知道这两者的关系。
小程序目前不支持直接引入 node_modules , 开发者需要使用到 node_modules 时候建议拷贝出相关的代码到小程序的目录中。
// common.js

  1. function sayHello(name) {
  2. console.log(`Hello ${name} !`)
  3. }
  4. function sayGoodbye(name) {
  5. console.log(`Goodbye ${name} !`)
  6. }
  7. module.exports.sayHello = sayHello
  8. exports.sayGoodbye = sayGoodbye

在需要使用这些模块的文件中,使用 require(path) 将公共代码引入

  1. var common = require('common.js')
  2. Page({
  3. helloMINA: function() {
  4. common.sayHello('MINA')
  5. },
  6. goodbyeMINA: function() {
  7. common.sayGoodbye('MINA')
  8. }
  9. })

7.视图层

(1) WXML
WXML(WeiXin Markup Language)是框架设计的一套标签语言,结合基础组件、事件系统,可以构建出页面的结构。
用以下一些简单的例子来看看 WXML 具有什么能力:
数据绑定:

  1. <!--wxml-->
  2. <view> {
  3. {message}} </view>
  4. // page.js
  5. Page({
  6. data: {
  7. message: 'Hello MINA!'
  8. }
  9. })

列表渲染

  1. <!--wxml-->
  2. <view wx:for="{
  3. {array}}"> {
  4. {item}} </view>
  5. // page.js
  6. Page({
  7. data: {
  8. array: [1, 2, 3, 4, 5]
  9. }
  10. })

条件渲染

  1. <!--wxml-->
  2. <view wx:if="{
  3. {view == 'WEBVIEW'}}"> WEBVIEW </view>
  4. <view wx:elif="{
  5. {view == 'APP'}}"> APP </view>
  6. <view wx:else="{
  7. {view == 'MINA'}}"> MINA </view>
  8. // page.js
  9. Page({
  10. data: {
  11. view: 'MINA'
  12. }
  13. })

模板

  1. <!--wxml-->
  2. <template name="staffName">
  3. <view>
  4. FirstName: {
  5. {firstName}}, LastName: {
  6. {lastName}}
  7. </view>
  8. </template>
  9. <template is="staffName" data="{
  10. {...staffA}}"></template>
  11. <template is="staffName" data="{
  12. {...staffB}}"></template>
  13. <template is="staffName" data="{
  14. {...staffC}}"></template>
  15. // page.js
  16. Page({
  17. data: {
  18. staffA: {firstName: 'Hulk', lastName: 'Hu'},
  19. staffB: {firstName: 'Shang', lastName: 'You'},
  20. staffC: {firstName: 'Gideon', lastName: 'Lin'}
  21. }
  22. })

事件

  1. <view bindtap="add"> {
  2. {count}} </view>
  3. Page({
  4. data: {
  5. count: 1
  6. },
  7. add: function(e) {
  8. this.setData({
  9. count: this.data.count + 1
  10. })
  11. }
  12. })

(2) WXSS
尺寸单位
rpx(responsive pixel): 可以根据屏幕宽度进行自适应。规定屏幕宽为750rpx。如在 iPhone6 上,屏幕宽度为375px,共有750个物理像素,则750rpx = 375px = 750物理像素,1rpx = 0.5px = 1物理像素。
图片描述

样式导入
使用@import语句可以导入外联样式表,@import后跟需要导入的外联样式表的相对路径,用;表示语句结束。
示例代码:

  1. /** common.wxss **/
  2. .small-p {
  3. padding:5px;
  4. }
  5. /** app.wxss **/
  6. @import "common.wxss";
  7. .middle-p {
  8. padding:15px;
  9. }

内联样式
框架组件上支持使用 style、class 属性来控制组件的样式。
style:静态的样式统一写到 class 中。style 接收动态的样式,在运行时会进行解析,请尽量避免将静态的样式写进 style 中,以免影响渲染速度。

  1. <view style="color:{
  2. {color}};" />

class:用于指定样式规则,其属性值是样式规则中类选择器名(样式类名)的集合,样式类名不需要带上.,样式类名之间用空格分隔。

  1. <view class="normal_view" />

选择器
目前支持的选择器有:
图片描述

全局样式与局部样式
定义在 app.wxss 中的样式为全局样式,作用于每一个页面。在 page 的 wxss 文件中定义的样式为局部样式,只作用在对应的页面,并会覆盖 app.wxss 中相同的选择器。

8.组件

(1)视图容器:

  1. view
  2. scroll-view
  3. swiper

(2)基础内容:

  1. icon
  2. text
  3. progress

(3)表单组件:

  1. button
  2. checkbox
  3. form
  4. input
  5. label
  6. picker
  7. picker-view
  8. radio
  9. slider
  10. switch
  11. textarea

(4)导航组件:

  1. navigator

(5)媒体组件:

  1. audio
  2. image
  3. video

(6)地图:

  1. map

(7)画布:

  1. canvas

(8)客服会话:

  1. contact-button

9.API

(1)网络
(2)媒体
(3)文件
(4)数据缓存
(5)位置
(6)设备
(7)界面
(8)开放接口

发表评论

表情:
评论列表 (有 0 条评论,774人围观)

还没有评论,来说两句吧...

相关阅读

    相关 程序

    微信小程序:             app.js:小程序的入口,全局变量以及获取用户信息都存放在这里。 app.json:界面的路径(会自动生成),tarBar在这里

    相关 程序

    个人中心页面 ![在这里插入图片描述][70] 保障页面![70 1][] 主页面![在这里插入图片描述][70 2]充值![在这里插入图片描述][70 3]骑行页

    相关 程序

    界面层: 事件: 给组件添加bind+事件名,在js里的page(\{\})写方法 阻止事件冒泡catch+事件名 绑定事件,阻止事件冒泡 事件传参 通