search
HomeWeb Front-endJS TutorialInstructions for using the Player component in vue-music

This article mainly introduces the relevant information of vue-music on the Player player component in detail. It has certain reference value. Interested friends can refer to it.

The examples in this article are shared with everyone. The specific content of the Player component is provided for your reference. The specific content is as follows

Mini player:

# #1. The player component will be opened on each page. First define the global player state in vuex state.js

import {playMode} from 'common/js/config.js';

const state = {
 singer:{}, 
 playing:false, //是否播放
 fullScreen:false, //是否全屏
 playList:[], //播放列表
 sequenceList:[], // 非顺序播放列表
 mode:playMode.sequence, // 播放模式(顺序0,循环1,随机2)
 currentIndex:-1, //当前播放索引
}
export default state 


---------------------------------------------
// config.js

export const playMode = {
 sequence:0,
 loop:1,
 random:2
}

2. Get the playlist data when entering the player page, change the playback state and open it in the music-list list

In song The -list component dispatches events to the parent component, and passes in the information and index of the current song

<li @click="selectItem(song,index)" v-for="(song,index) in songs" class="item">

------------------------------
selectItem(item,index){
 this.$emit(&#39;select&#39;,item,index)
},

Receives dispatched events in the music-list component.

<song-list :rank="rank" :songs="songs" @select="selectItem"></song-list>

3. If you commit multiple states, set them in actions

import {playMode} from &#39;common/js/config.js&#39;

export const selectPlay = function({commit,state},{list,index}){
 commit(types.SET_SEQUENCE_LIST, list)
 commit(types.SET_PLAYLIST, list)
 commit(types.SET_CURRENT_INDEX, index)
 commit(types.SET_FULL_SCREEN, true)
 commit(types.SET_PLAYING_STATE, true)
}

4. Use mapActions to submit the changed value in the music-list component

import {mapActions} from &#39;vuex&#39;

methods:{
 selectItem(item,index){
  this.selectPlay({
  list:this.songs,
  index
  })
 },
 ...mapActions([
  &#39;selectPlay&#39;
 ])
 },

5. In palyer Get the vuex global status and assign the status to the corresponding location (the code is the complete code, please understand it slowly according to the explanation later)

<p class="player" v-show="playList.length>0">    // 如果有列表数据则显示
  <p class="normal-player" v-show="fullScreen">  //如果全屏
   <p class="background">
   <img src="/static/imghwm/default1.png"  data-src="currentSong.image"  class="lazy"  : alt=""    style="max-width:90%"  style="max-width:90%">    //模糊背景图
   </p>
   <p class="top">
    <p class="back" @click="back">
    <i class="icon-back"></i>
    </p>
    <h1 class="title" v-html="currentSong.name"></h1>    //当前歌曲名称
    <h2 class="subtitle" v-html="currentSong.singer"></h2>  //当前歌手名
   </p>
   <p class="middle">
    <p class="middle-l">
    <p class="cd-wrapper">
     <p class="cd" :class="cdCls">
     <img class="image lazy"  src="/static/imghwm/default1.png"  data-src="currentSong.image"  : alt="" >    //封面图
     </p>
    </p>
    </p>
   </p>
   <p class="bottom">
   <p class="progress-wrapper">
   <span class="time time-l">{{ format(currentTime) }}</span>
   <p class="progress-bar-wrapper">
    <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
   </p>
   <span class="time time-r">{{ format(currentSong.duration) }}</span>
   </p>
     <p class="operators">
    <p class="icon i-left">
     <i :class="iconMode" @click="changeMode"></i>
    </p>
     <p class="icon i-left" :class="disableCls">
      <i @click="prev" class="icon-prev"></i>
      </p>
      <p class="icon i-center" :class="disableCls">
      <i :class="playIcon" @click="togglePlaying"></i>
      </p>
      <p class="icon i-right" :class="disableCls">
      <i @click="next" class="icon-next"></i>
      </p>
      <p class="icon i-right">
      <i class="icon icon-not-favorite"></i>
      </p>
    </p>
    </p>
   </p>
   </transition>
   <transition name="mini">
    <p class="mini-player" v-show="!fullScreen" @click="open">
     <p class="icon">
      <img class="cdCls lazy"  src="/static/imghwm/default1.png"  data-src="currentSong.image"  : alt=""    style="max-width:90%"  style="max-width:90%" :>
     </p>
     <p class="text">
      <h2 class="name" v-html="currentSong.name"></h2>
      <p class="desc" v-html="currentSong.singer"></p>
     </p>
     <p class="control">
      <i :class="miniIcon" @click.stop="togglePlaying"></i>
     </p>
     <p class="control">
      <i class="icon-playlist"></i>
     </p>
    </p>
   </transition>
   <audio :src="currentSong.url" ref="audio" @canplay="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
 </p>

Open the status of the player

import {mapGetters,mapMutations} from &#39;vuex&#39;;

...mapGetters([
 &#39;fullScreen&#39;,
 &#39;playList&#39;,
 &#39;currentSong&#39;,
 &#39;playing&#39;,
 &#39;currentIndex&#39;,
])

Note: You cannot assign values ​​directly in the component The state this.fullScreen = false in modified vuex needs to be changed through mutations, define mutation-types and mutations, and then use the mapMutations proxy method of vuex to call

[types.SET_FULL_SCREEN](state, flag) {
 state.fullScreen = flag
 },

import {mapGetters,mapMutations} from &#39;vuex&#39;;
methods:{
 ...mapMutations({
 setFullScreen:"SET_FULL_SCREEN", 
 }),
 back(){
 this.setFullScreen(false)
 },
}

Set the click play button method

 <i :class="playIcon" @click="togglePlaying"></i>
togglePlaying(){
 this.setPlayingState(!this.playing); //改变全局变量playing 的属性
},

// 然后watch 监听playing 操作实际的audio 标签的播放暂停
watch:{
  playing(newPlaying){
   let audio = this.$refs.audio;
   this.$nextTick(() => {
    newPlaying ? audio.play():audio.pause();
   })
  }
 },

// 用计算属性改变相应的播放暂停图标
playIcon(){
 return this.playing? &#39;icon-pause&#39;:&#39;icon-play&#39;
},

Set the click Play previous and next song button methods. Use mapGetters to get the value of currentIndex (plus one or minus one) and change it, thereby changing the state of currentSong and listening for switching playback. Determine playlist limit reset.

prev(){
    if(!this.songReady){
      return;
    }

 let index = this.currentIndex - 1;
 if(index === -1){    //判断播放列表界限重置
  index = this.playList.length-1;
 }
 this.setCurrentIndex(index);
 if(!this.playing){  //判断是否播放改变播放暂停的icon
  this.togglePlaying();
 }
 this.songReady = false;
},
next(){
 if(!this.songReady){
    return;
   }
 let index = this.currentIndex + 1;
 if(index === this.playList.length){    //判断播放列表界限重置
  index = 0;
 }
 this.setCurrentIndex(index);
 if(!this.playing){
  this.togglePlaying();
 }
 this.songReady = false;
},

Listen to the canpaly event of the audio element tag, when the song is loaded, and the error event, when an error occurs in the song, provide user experience to prevent users from quickly switching and causing errors.

Set the songReady flag. If the song is not ready, directly return false when clicking the next song

data(){
 return {
  songReady:false,
 }
},

ready(){
 this.songReady = true;
},
error(){
 this.songReady = true;
},

Progress bar

audio element monitors timeupdate The event obtains the readable and writable attribute timestamp of the current playback time. Use formt for formatting time processing, (_pad is a zero-padding function)

Get the total audio duration currentSong.duration

<p class="progress-wrapper">
 <span class="time time-l">{{ format(currentTime) }}</span>
 <p class="progress-bar-wrapper">
 <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
 </p>
 <span class="time time-r">{{ format(currentSong.duration) }}</span>
</p>

<audio :src="currentSong.url" ref="audio" @canplay="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
updateTime(e){
 this.currentTime = e.target.currentTime; // 获取当前播放时间段
},

format(interval){
 interval = interval | 0;
 const minute = interval/60 | 0;
 const second = this._pad(interval % 60);
 return `${minute}:${second}`;  
},

_pad(num,n=2){
 let len = num.toString().length;
 while(len<n){
 num = &#39;0&#39; + num;
 len ++;
 }
 return num;
},

Create a progress-bar component to receive the pencent progress parameter, and set the progress bar width and The position of the ball. The player component sets the calculated property percent

percent(){
 return this.currentTime / this.currentSong.duration  // 当前时长除以总时长
},

progress-bar component

<p class="progress-bar" ref="progressBar" @click="progressClick">
 <p class="bar-inner">
  <p class="progress" ref="progress"></p>
  <p class="progress-btn-wrapper" ref="progressBtn"
   @touchstart.prevent="progressTouchStart"
   @touchmove.prevent="progressTouchMove"
   @touchend="progressTouchEnd"  
  >
  <p class="progress-btn"></p>
  </p>
 </p>
 </p>
const progressBtnWidth = 16 //小球宽度

props:{
 percent:{
 type:Number,
 default:0
 }
},


watch:{
 percent(newPercent){
 if(newPercent>=0 && !this.touch.initated){    
  const barWidth = this.$refs.progressBar.clientWidth - progressBtnWidth;
  const offsetWidth = newPercent * barWidth;
  this.$refs.progress.style.width = `${offsetWidth}px`;
  this.$refs.progressBtn.style.transform=`translate3d(${offsetWidth}px,0,0)`
 }
 }
}

Set the drag

small button on the progress bar Add touchstart, touchmove, touchend event listening methods to progressBtn, add prevent to the event to prevent the default browser behavior of dragging, and obtain dragging information for calculation

Create a touch object on the instance to maintain the relationship between different callbacks Communications share status information. In the touchstart event method, first set this.touch.initiated to true, indicating that dragging has started. Record the starting click position e.touches[0].pageX and save it to the touch object to record the current progress width.

In touchmove, first determine whether the touchstart method has been entered first, and calculate the moved position minus the offset length of the click start position. let deltax = e.touches[0].pageX - this.touch.startX

can set the existing length of the progress bar plus the offset length. The maximum width cannot exceed the width of the parent progressbar

Call this._offset(offsetWidth) method to set the width of the progress bar

Set this.touch.initiated to false in the touchend event method to indicate dragging End, and dispatch the event to the player component. Set the currentTime value of audio to the correct value, and the parameter is pencent

Add a click event in the progressbar, call this._offset(e.offsetX), and dispatch the event

 created(){
 this.touch = {};
 },

methods:{
 progressTouchStart(e){
 this.touch.initiated = true;
 this.touch.startX = e.touches[0].pageX;
 this.touch.left = this.$refs.progress.clientWidth;
 },
 progressTouchMove(e){
 if(!this.touch.initiated){
  return;
 }
 let deltaX = e.touches[0].pageX - this.touch.startX;
 let offsetWidth = Math.min(this.$refs.progressBar.clientWidth - progressBtnWidth,Math.max(0,this.touch.left + deltaX));
 this._offset(offsetWidth);
 },
 progressTouchEnd(e){
 this.touch.initiated = false;
 this._triggerPercent();
 },
 progressClick(e){
 const rect = this.$refs.progressBar.getBoundingClientRect();
 const offsetWidth = e.pageX - rect.left;
 this._offset(offsetWidth);
 // this._offset(e.offsetX);
 this._triggerPercent();
 },
 _offset(offsetWidth){
 this.$refs.progress.style.width = `${offsetWidth}px`;
 this.$refs.progressBtn.style[transform] = `translate3d(${offsetWidth}px,0,0)`;
 },
 _triggerPercent(){
 const barWidth = this.$refs.progressBar.clientWidth - progressBtnWidth;
 const percent = this.$refs.progress.clientWidth / barWidth;
 this.$emit("percentChange",percent)
 }
},

This article has been compiled into the "Vue.js Front-end Component Learning Tutorial". Everyone is welcome to learn and read.

For tutorials on vue.js components, please click on the special vue.js component learning tutorial to learn.

For more vue learning tutorials, please read the special topic "Vue Practical Tutorial"

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to integrate the carousel image in mint-ui in vue.js

How to implement it in Jstree Disabled child nodes will also be selected when the parent node is selected

About the usage of filters in Vue

Adaptive in Javascript Approach

The above is the detailed content of Instructions for using the Player component in vue-music. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft