25.1 npm模块的使用
-
开启 npm 模块的支持 就是
JS es5
那个。
-
然后 npm 初始化
npm init
一路回车即可。你就会发现 在 项目目录下生成了一个package.json
- 使用 PubsubJS
直接cmd窗口 输入:npm install pubsub-js
就可以 下载这个 npm 包了。
- 然后 需要通讯的页面 上面 引入 这个 包。比如说
songDetail
和recommendSong
我们 做一个 上一首 和 下一首 的功能。就需要用到 页面通讯。
- 构建 npm
开发工具 → 工具 → 构建 npm
会出现 两个文件夹:
25.2 PubSubJS 实现页面通讯
PubSub.publish('订阅的名字', 传递过去的数据)
:只要 有 相同的 这个 名字 那么 就 发送到 那个 订阅上去。
PubSub.subscribe('订阅的名字', (msg, 接收数据的参数) => {})
:拿到 同样名字的 publish 传递的数据。
Pubsub.unsubscribe('订阅的名字')
:销毁这个 订阅,否则会浪费 资源。
主要其实 就上上述 这三个 方法,自己 写着玩 都能写好。完全没有任何 难度。
songDetail.wxml
给 对应的 上一首 和 下一首 组件 添加 事件 和 id。
<view class="musicControl">
<text class="iconfont icon-zhongbo"></text>
<text id="pre" class="iconfont icon-shangyishoushangyige" bindtap="handleSwitch"></text>
<text class="iconfont {{isPlay? 'icon-zanting':'icon-bofang'}} big" bindtap="handleMusicPlay"></text>
<text id="next" class="iconfont icon-xiayigexiayishou" bindtap="handleSwitch"></text>
<text class="iconfont icon-24gl-playlistMusic5"></text>
</view>
id 的作用 是 为了 区别 你点击的 事件 是哪个。
recommendSong.wxml
在这里 给 对应的 点击事件那个 组件 添加 一个data-index
这样的话 我们 就能够 O(1) 拿到 这个 下标。
<scroll-view scroll-y="true" class="listScroll">
<view class="scrollItem" bindtap="navigateTosongDetail" data-song="{{item}}" data-index="{{index}}" wx:for="{{recommendList}}" wx:key="id">
<image src="{{item.al.picUrl}}"></image>
<view class="musicInfo">
<text class="musicName">{{item.al.name}}</text>
<text class="author">{{item.ar[0].name}}</text>
</view>
<text class="iconfont icon-gengduo-shuxiang"></text>
</view>
</scroll-view>
songDetail.js 点击的回调 那里 设定 订阅接收 和 发送
// 点击切歌的回调
handleSwitch(event){
// 1. PubSubJS 的实现方法
// 获取切歌的类型
let type = event.currentTarget.id;
PubSub.publish('switchType', type);
PubSub.subscribe('musicId', (msg, musicId) => {
console.log(musicId); // 打印输出一下 musicId
});
},
recommendSong.js 点击的回调 那里 设定 订阅接收 和 发送
/**
* 生命周期函数--监听页面加载
*/ async onLoad(options) {
// 判断是否登录
let userInfo = wx.getStorageSync('userInfo');
if (!userInfo) {
wx.showToast({
title: "请先登录",
icon: 'none',
success: () => {
wx.relaunch({
url: '/pages/login/login'
})
}
})
}
this.setData({
day: new Date().getDate(),
month: new Date().getMonth() + 1
});
this.getReconmmendList();
// 订阅来自 songDetail 页面传递过来的 数据
PubSub.subscribe('switchType', (msg, switchType) => {
if(switchType == "pre"){
this.setData({
index: this.data.index - 1 < 0 ? 0 : this.data.index - 1
})
}else{
this.setData({
index: this.data.index + 1 > 29 ? 0 : this.data.index + 1
})
}
let musicId = this.data.recommendList[this.data.index].id;
PubSub.publish('musicId', musicId);
});
},
大功告成,其实 用 官方的 eventChannel
其实 也可以实现,只不过 我们 多 掌握 一种方法 不失为 一个 坏事。低版本的 小程序 也还没有支持 这个 eventChannel
呢。到时候 你开发个 低版本的小程序,可不就得 用 PubSubJS 嘛。