微信小程序 -订阅发布模式

图形展示:

代码展示:

1. 安装模块 pubsub-js

npm i pubsub-js --save

2. 导入模块(在需要订阅发布的 js 页面内进行导入)

import PubSub from 'pubsub-js'

注:在微信小程序中无法直接npm 下载 导入 的(安装一个就需要构建一次)

解决:菜单栏 --> 工具 -->  构建 npm  点击即可(会出现新的目录)

详情页:

1. 绑定两个事件,用于在点击 prev(上一页)  next(下一页) 时触发事件

wxml页面:

<viewclass="musicControl">
    <text class="iconfont icon-iconsMusicyemianbofangmoshiShuffle"></text>
    <text
        class="iconfont icon-shangyishou"
        id="pre"
        bindtap="switchMusic"  //绑定事件
    ></text>
    <text
        class="iconfont {{isPlay ? "icon-zanting':'icon-bofang' } big"
        bindtap="musicPlay"  
    ></text>
    <text 
        class="iconfont icon-next" 
        id="next bindtap="switchMusic'  //绑定事件
    ></text>
    <text class="iconfont icon-iconsMusicyemianbofangmoshiplayList"></text>
</view>

2. 触发事件,使用 PubSub 的 publish 方法进行发布 

js页面:

switchMusic(e){
    //是需要向歌曲列表页进行信息的发布
    const type = e.currentTarget.id;
    PubSub.publish("switchType",type);
},

3. 在生命周期 onLoad 中 使用 PubSubsubscribe 方法对列表页发布的内容进行订阅

有两个参数:

        参数一:要订阅的发布名称

        参数二:回调函数,处理订阅的 发布信息内容

                函数参数一 (msg):发布的对应名称  如:PubSub.publish("musicId",musicId);

                函数参数二 (musicId):发布的对应参数  如:PubSub.publish("musicId",musicId);
 

onLoad(options) {
    PubSub.subscribe("musicId",(msg, musicId) => {
        console.log("musicId:", musicId);
    });
},

列表页:
1. 在生命周期 onLoad 中 使用 PubSub 的 subscribe 方法对详情页发布的内容进行订阅

有两个参数:

        参数一:要订阅的发布名称

        参数二:回调函数,处理订阅的 发布信息内容

                函数参数一 (msg):发布的对应名称  如:  PubSub.publish("switchType",type);

                函数参数二 (type):发布的对应参数  如: PubSub.publish("switchType",type);
 

onLoad(options) {
    PubSub.subscribe("switchType",(msg, type) => {
        let { index, recommendList } = this.data;
        
        // 控制边界
        if(type === "next") {
            index === recommendList.length -1 && (index = -1);
            // 下一首
            index += 1;
        } else {
            index === 0 && (index = recommendList.length);
            //上一首
            index -= 1;
        }
        console.log(index);
    });
},

2. 处理完数据后,在下方使用 PubSub 的 publish 方法进行发布

onLoad(options) {
    PubSub.subscribe("switchType",(msg, type) => {
        let { index, recommendList } = this.data;
 
        if(type === "next") {
            // 下一首
            index += 1;
        } else {
            //上一首
            index -= 1;
        }
        console.log(index);
        let musicId = recommendList[index].id;
        PubSub.publish("musicId",musicId); //将音乐id发布到详情页
        this.setData({
            index,
        });
    });
},

  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值