微信小程序起步

小程序

一、小程序起步

1.微信小程序官网](https://mp.weixin.qq.com/cgi-bin/wx)注册账号

2.进入官网看文档

二、微信小程序路由配置

  • pages里面新建pages会在pack.json自动生成路由
1
2
3
4
5
6
7
"pages": [
"pages/index/index",
"pages/logs/logs",
"pages/mine/mine",
"pages/serach/search",
"pages/find/find"
],
  • tabBar写在window后面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"tabBar": {
"selectedColor": "#666", //选中时的样式
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "./pages/images/首页-未选中.png", //字体图标路径
"selectedIconPath": "./pages/images/首页-选中.png" //选中时字体图标路径
},
{
"pagePath": "pages/serach/search",
"text": "发现",
"iconPath": "./pages/images/发现未选中.png",
"selectedIconPath": "./pages/images/发现-选中.png"
},
{
"pagePath": "pages/logs/logs",
"text": "日志",
"iconPath": "./pages/images/日志.png",
"selectedIconPath": "./pages/images/日志选中.png"
},
{
"pagePath": "pages/mine/mine",
"text": "我的",
"iconPath": "./pages/images/我 的.png",
"selectedIconPath": "./pages/images/我的选中.png"
}
]
},

三、数据绑定及渲染

1.渲染

1
2
3
4
5
6
7
<view> {{ message }} </view>

Page({
data: {
message: 'Hello MINA!'
}
})
  • wx:if用法
    1
    2
    3
    > 备注:这种属性方法的都要用`"{{}}"`这种形式,例如,`wx:for="{{}}"`、
    >
    > `wx:if="{{}}"`、`checked="{{false}}"`,还有三元运算`hidden="{{flag ? true : false}}"`

2.列表渲染wx:for

1
2
3
> 在组件上使用 `wx:for` 控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。
>
> 默认数组的当前项的下标变量名默认为 `index`,数组当前项的变量名默认为 `item`
1
2
3
<view wx:for="{{array}}">
{{index}}: {{item.message}}
</view>

四、做音乐播放器小程序步骤

1.先创建你需要的页面及路由

1
> 例如:先创建一个首页、一个详情页、搜索页

2.引入weui 、search组件、pannel组件

3.新建components在里面写小组件

4.在index.js发起ajax请求,利用组件通信传到pannel组件里面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Page({
data:{
song_list:[], //定义一个空数组
offset:0
},
onReady(){
this.loadMore()
},
onLoad: function () {
this.setData({
icon20: base64.icon20,
icon60: base64.icon60
});
},
onPullDownRefresh() {
this.loadMore()
},
loadMore() {
var self = this;
wx.request({
url: 'https://tingapi.ting.baidu.com/v1/restserver/ting', //仅为示例,并非真实的接口地址
data: {
method: "baidu.ting.billboard.billList",
type: 1,
size: 10,
offset: this.data.offset
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
wx.stopPullDownRefresh()
self.setData({
offset:++self.data.offset
})
console.log(res.data.song_list)
//把请求回来的数据合并到空数组,因为是上拉刷新,所以就要用新数组合并旧数据,以达到每次上面都是新的
self.setData({
song_list: res.data.song_list.concat(self.data.song_list)
})
}
})
}

5.利用组件通信传数据到子组件

1
<xpannel songList="{{song_list}}"></xpannel>

6.接收父组件传过来的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
properties: {
songList: { // 属性名
type: Array, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
value: '', // 属性初始值(可选),如果未指定则会根据类型选择一个
observer: function (newVal, oldVal, changedPath) {
console.log(newVal)
this.setData({
song: newVal //把接收过来的数组存到本地
})
// 属性被改变时执行的函数(可选),也可以写成在methods段中定义的方法名字符串, 如:'_propertyChange'
// 通常 newVal 就是新设置的数据, oldVal 是旧数据
}
},
},

7.动态渲染接收过来的数据

1
2
3
4
5
6
7
8
9
<navigator url="{{'/pages/detail/detail?songId='+item.song_id}}" wx:for="{{song}}" 		class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active">
<view class="weui-media-box__hd weui-media-box__hd_in-appmsg">
<image class="weui-media-box__thumb" src="{{item.pic_big}}" />
</view>
<view class="weui-media-box__bd weui-media-box__bd_in-appmsg">
<view class="weui-media-box__title">{{item.album_title}}</view>
<view class="weui-media-box__desc">{{item.country}}-{{item.author}}</view>
</view>
</navigator>

8.传songid到详情页

1
> 传songid到详情页的目的是,让详情页根据你传过来的id发起ajax请求,渲染数据
1
2
3
<navigator url="{{'/pages/detail/detail?songId='+item.song_id}}" wx:for="{{song}}" class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active">

备注:通过拼接字符串的形式传送 url="{{'/pages/detail/detail?songId='+item.song_id}}"

9.接收传过来的id,设置给本地变量

1
2
3
4
5
6
7
8
9
10
11
  onLoad: function (options) {
// console.log(options.songId)
this.setData({
songId: options.songId
})

this.getSong();
this.getlrc()
console.log(this.data.songId)
}
备注:`options`为形参,好比vue和react中的`props`

10.在详情页引入audio组件

  • html页面
1
2
3
4
5
6
7
<!-- audio.wxml -->
<audio poster="{{poster}}" name="{{name}}" author="{{author}}" src="{{src}}" id="myAudio" controls loop></audio>

<button type="primary" bindtap="audioPlay">播放</button>
<button type="primary" bindtap="audioPause">暂停</button>
<button type="primary" bindtap="audio14">设置当前播放时间为14秒</button>
<button type="primary" bindtap="audioStart">回到开头</button>
  • js页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// audio.js
Page({
onReady: function (e) {
// 使用 wx.createAudioContext 获取 audio 上下文 context
this.audioCtx = wx.createAudioContext('myAudio')
},
data: {
poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
name: '此时此刻',
author: '许巍',
src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
},
audioPlay: function () {
this.audioCtx.play()
},
audioPause: function () {
this.audioCtx.pause()
},
audio14: function () {
this.audioCtx.seek(14)
},
audioStart: function () {
this.audioCtx.seek(0)
}
})

11.把引入的audio参数全变成变量

1
2
3
4
5
6
7
8
9
data: {
songId:"",
poster: '',
name: '',
author: '',
src: '',
lrc:"",
time:0
},

12.发起ajax请求把请求回来的数据赋给data里面的变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
getSong() {
var self = this;
wx.request({
url: 'https://tingapi.ting.baidu.com/v1/restserver/ting', //仅为示例,并非真实的接口地址
data: {
method:"baidu.ting.song.play",
songid:this.data.songId
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log(res.data)
self.setData({
poster: res.data.songinfo.pic_big,
name: res.data.songinfo.title,
author: res.data.songinfo.author,
src: res.data.bitrate.file_link
})
}
})
}
备注:此时就可以播放歌曲了

13.歌词处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
getlrc() {
var self = this;
wx.request({
url: 'https://tingapi.ting.baidu.com/v1/restserver/ting', //仅为示例,并非真实的接口地址
data: {
method:"baidu.ting.song.lry",
songid:this.data.songId
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
// console.log(res.data)
let obj = self.parseLyric(res.data.lrcContent) //执行函数拿到歌词
console.log(obj)
self.setData({
lrc: obj
})


}
})
},
//把歌词处理成一段一段的
parseLyric(lrc) {
var lyrics = lrc.split("\n");
var lrcObj = {};
for (var i = 0; i < lyrics.length; i++) {
var lyric = decodeURIComponent(lyrics[i]);
var timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
var timeRegExpArr = lyric.match(timeReg);
if (!timeRegExpArr) continue;
var clause = lyric.replace(timeReg, '');
for (var k = 0, h = timeRegExpArr.length; k < h; k++) {
var t = timeRegExpArr[k];
var min = Number(String(t.match(/\[\d*/i)).slice(1)),
sec = Number(String(t.match(/\:\d*/i)).slice(1));
var time = min * 60 + sec;
lrcObj[time] = clause;
}
}
return lrcObj;
},

14.渲染歌词

1
> 你可以在本地设置个时间为time:0,然后再设置个定时器,让time每秒+1,根据time渲染歌词
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
   data: {
songId:"",
poster: '',
name: '',
author: '',
src: '',
lrc:"",
time:0 //设置tiem
},
======================
audioPlay: function () {
this.audioCtx.play();
timer=setInterval(() => {
this.setData({
time: ++this.data.time
})
},1000)
},
//按暂停时清除定时器
audioPause: function () {
this.audioCtx.pause();
clearInterval(timer);
},
//渲染歌词
<text>{{lrc[time]}}</text>

15.搜索歌曲做法

1
2
3
> 1.serach组件复用`<xsearchBar status="find"></xsearchBar> `
>
> 2.接收search`status`
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  properties: {
status: String // 简化的定义方式
},
===============================
ready() {
console.log(this.data.inputVal)
if (this.data.status == "find") {
this.setData({
inputShowed: true //显示取消和输入光标
});
} else {
this.setData({
inputShowed: false
});
}
}
1
> 3.点击取消回到首页
1
2
3
4
showInput: function () {
wx.navigateTo({
url: "/pages/find/find"
})
1
> 4.输入文字发起ajax请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
data: {
inputShowed: false,
inputVal: "",
renderSong:[]
},
===================================
inputTyping: function (e) {
this.searchSong(e.detail.value) //执行搜索歌曲函数,传入输入框的`value`
this.setData({
inputVal: e.detail.value
});

console.log(this.data.inputVal)
},
===========================================
searchSong(keyword) {
var self = this;
wx.request({
url: 'https://tingapi.ting.baidu.com/v1/restserver/ting', //仅为示例,并非真实的接口地址
data: {
method: "baidu.ting.search.catalogSug",
query: keyword
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log(res.data)
self.setData({
renderSong: res.data.song ? res.data.song:"" //把得到的数据赋给本地变量
})

console.log(self.renderSong)
}
})
},

16.点击的时候把数据传到详情页

1
2
3
4
5
6
<navigator url="{{'/pages/detail/detail?songId='+item.songid}}" class="weui-cell" wx:for="{{renderSong}}" hover-class="weui-cell_active">
<view class="weui-cell__bd">
<view>{{item.artistname}}-{{item.songname}}</view>
</view>
</navigator>
备注:传songid到详情页 url="{{'/pages/detail/detail?songId='+item.songid}}"