微信小程序 25 npm模块和PubSubJS实现页面通讯

25.1 npm模块的使用


  1. 开启 npm 模块的支持 就是 JS es5 那个。
    在这里插入图片描述

  2. 然后 npm 初始化 npm init 一路回车即可。你就会发现 在 项目目录下生成了一个 package.json

在这里插入图片描述

  1. 使用 PubsubJS

直接cmd窗口 输入:npm install pubsub-js 就可以 下载这个 npm 包了。

在这里插入图片描述

  1. 然后 需要通讯的页面 上面 引入 这个 包。比如说 songDetailrecommendSong 我们 做一个 上一首 和 下一首 的功能。就需要用到 页面通讯。

在这里插入图片描述在这里插入图片描述

  1. 构建 npm

开发工具 → 工具 → 构建 npm

在这里插入图片描述
会出现 两个文件夹:

在这里插入图片描述


25.2 PubSubJS 实现页面通讯

PubSub.publish('订阅的名字', 传递过去的数据):只要 有 相同的 这个 名字 那么 就 发送到 那个 订阅上去。

PubSub.subscribe('订阅的名字', (msg, 接收数据的参数) => {}):拿到 同样名字的 publish 传递的数据。

Pubsub.unsubscribe('订阅的名字'):销毁这个 订阅,否则会浪费 资源。

主要其实 就上上述 这三个 方法,自己 写着玩 都能写好。完全没有任何 难度。

  1. 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 的作用 是 为了 区别 你点击的 事件 是哪个。

  1. 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>
  1. songDetail.js 点击的回调 那里 设定 订阅接收 和 发送
    // 点击切歌的回调
    handleSwitch(event){

        // 1. PubSubJS 的实现方法
        // 获取切歌的类型
        let type = event.currentTarget.id;
        PubSub.publish('switchType', type);
        PubSub.subscribe('musicId', (msg, musicId) => {
            console.log(musicId); // 打印输出一下 musicId
        });

    },
  1. 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 嘛。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值