Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化播放器组件play.vue在多个组件中都有使用,因此放在app.vue中,同时基于vuex进行管理
1.组件放置在app.vue中
<template>
<div id="app">
<m-header></m-header>
<tab></tab>
<keep-alive>
<router-view></router-view>
</keep-alive>
<player></player>
</div>
</template>
2.state.js定义状态
import {playMode} from 'common/js/config'
const state = {
singer: {},
playing: false, //playing: 播放状态
fullScreen: false, //fullScreen: 是否全屏(normal播放器/mini播放器)
playlist: [], //点击前进、后退实际是有一个播放列表:playlist
sequenceList: [], //sequenceList顺序播放列表
mode: playMode.sequence, //mode:播放模式 0顺序 1 循环 2 随机
currentIndex: -1, //currentIndex 当前播放的歌曲
disc: {},
topList: {}
}
export default state
3.获取state的一些状态getter.js
需要从 store 中的 state 中派生出一些状态,Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)
export const singer = state => state.singer
export const playing = state => state.playing
export const fullScreen = state => state.fullScreen
export const playlist = state => state.playlist
export const sequenceList = state => state.sequenceList
export const mode = state => state.mode
export const currentIndex = state => state.currentIndex
export const currentSong = (state) => {
return state.playlist[state.currentIndex] || {}
}
export const disc = state => state.disc
export const topList = state => state.topList
4.mutations.js
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
//使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式。
//这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然
export const SET_SINGER = 'SET_SINGER'
export const SET_PLAYING_STATE = 'SET_PLAYING_STATE'
export const SET_FULL_SCREEN = 'SET_FULL_SCREEN'
export const SET_PLAYLIST = 'SET_PLAYLIST'
export const SET_SEQUENCE_LIST = 'SET_SEQUENCE_LIST'
export const SET_PLAY_MODE = 'SET_PLAY_MODE'
export const SET_CURRENT_INDEX = 'SET_CURRENT_INDEX'
export const SET_DISC = 'SET_DISC'
export const SET_TOP_LIST = 'SET_TOP_LIST'
import * as types from './mutation-types'
const mutations = {
[types.SET_SINGER](state, singer) {
state.singer = singer
},
[types.SET_PLAYING_STATE](state, flag) {
state.playing = flag
},
[types.SET_FULL_SCREEN](state, flag) {
state.fullScreen = flag
},
[types.SET_PLAYLIST](state, list) {
state.playlist = list
},
[types.SET_SEQUENCE_LIST](state, list) {
state.sequenceList = list
},
[types.SET_PLAY_MODE](state, mode) {
state.mode = mode
},
[types.SET_CURRENT_INDEX](state, index) {
state.currentIndex = index
},
[types.SET_DISC](state, disc) {
state.disc = disc
},
[types.SET_TOP_LIST](state, topList) {
state.topList = topList
}
}
export default mutations
5.actions.js
actions应用场景:
- 异步操作
- 封装多个mutations更改state
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。