基础样式
v-show="fullScreen"控制播放器全屏展开还是收缩,
currentSong当前播放的歌曲
将不同的逻辑放到不同的文件中,相同的放到一个文件中
获取fullScreen和currentSong,使用useStore api拿数据
import { useStore } from 'vuex'
import { computed, watch, ref, nextTick } from 'vue'
setup() {
const store = useStore()
const fullScreen = computed(() => store.state.fullScreen)
const currentSong = computed(() => store.getters.currentSong)
}
播放器时全局组件 在app.vue引入注册
<template>
<m-header></m-header>
<tab></tab>
<router-view></router-view>
<player></player>
</template>
<script>
import Header from '@/components/header/header'
import Tab from '@/components/tab/tab'
import Player from '@/components/player/player'
export default {
components: {
Player,
MHeader: Header,
Tab
}
}
</script>
歌曲播放
watch api通过currentSong拿到url,赋值给audio,ref api 拿到audio
watch(currentSong, (newSong) => {
if (!newSong.id || !newSong.url) {
return
}
const audioEl = audioRef.value
audioEl.src = newSong.url
audioEl.play()
})
收缩
通过commit api提交一个mutation
function goBack() {
store.commit('setFullScreen', false)
}
播放按钮的暂停与播放
根据不同playing的播放状态求得playicon来改变图标
const playing = computed(() => store.state.playing)
const playIcon = computed(() => {
return playing.value ? 'icon-pause' : 'icon-play'
})
绑定点击事件 click=“togglePlay”
修改全局playing状态
function togglePlay() {
if (!songReady.value) {
return
}
store.commit('setPlayingState', !playing.value)
}
定义watch函数,看playing数据的变化,操作audio这个dom
watch(playing, (newPlaying) => {
if (!songReady.value) {
return
}
const audioEl = audioRef.value
if (newPlaying) {
audioEl.play()
playLyric()
} else {
audioEl.pause()
stopLyric()
}
})
audio自然暂停,使用pause同步
function pause() {
store.commit('setPlayingState', false)
}