微信小程序实现音乐播放器(3)(使用全局数据实现数据共享)

前情提要

每个小程序都需要在App.js中调用 App({}) 注册小程序实例。

App({
   
	globalData:{
   
		isPlayGlobal:false,
		musicIdGlobal:''
	}
})

整个小程序只有一个App实例,是全部页面共享的。可以通过 getApp() 获取到全局唯一的App实例,获得App上的数据或函数。

const appInstance = getApp();
const {
   isPlayGlobal,musicIdGlobal} = appInstance.globalData;

搭建静态资源服务器

  1. 全局安装serve:npm install -g serve
  2. 在任何你想的地方新建文件夹:resources。resources下新建文件夹:images,用于存放静态图片资源;resources下新建文件夹:videos,用于存放视频文件;resources下新建文件夹:audios,用于存放音频文件。
  3. 启动服务器:serve resources

小程序项目

代码涉及的主要文件有:

  1. app.json
  2. app.js
  3. app.wxss
  4. pages/index/index.json
  5. pages/index/index.wxml
  6. pages/index/index.wxss
  7. pages/index/index.js
  8. pages/music/music.json
  9. pages/music/music.wxml
  10. pages/music/music.wxss
  11. pages/music/music.js

在这里插入图片描述

app.json

{
   
  "pages": [
    "pages/index/index",
    "pages/music/music"
  ],
  "window": {
   
    "navigationBarBackgroundColor": "#624d2e",
    "navigationBarTitleText": "首页",
    "navigationBarTextStyle": "white"
  },
  "requiredBackgroundModes": [
    "audio"
  ],
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

app.js

App({
   
  globalData:{
   
    isPlayGlobal:false,   //当前是否有歌曲在播放
    musicIdGlobal:''     //当前正在播放的歌曲是哪首
  }
})

app.wxss

page{
   
  height: 100%;
}

pages/index/index.json

{
   
  "usingComponents": {
   },
  "navigationBarTitleText": "播放列表"
}

pages/index/index.wxml

<view class="index-container">
  <view class="header">
    <image src="/static/images/icon-play-square.png"></image>
    <text>播放全部</text>
    <text>{
  {musicList.length}}</text>
  </view>
  <scroll-view class="music-list" enable-flex scroll-y >
    <view class="music-item" wx:for="{
    {musicList}}" wx:key="id" bindtap="handleTap" data-musicitem="{
    {item}}">
      <view class="music-index">{
  {index+1}}</view>
      <image class="music-image" src="{
    {item.picUrl}}"></image>
      <view class="music-info">
        <view class="musci-name">{
  {item.name}}</view>
        <view class="music-author">{
  {item.author}}</view>
      </view>
      <image class="btn-more" src="/static/images/icon-more.png"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值