Vuex的各个模块封装

一、各个模块的作用:

state 用来数据共享数据存储
mutation 用来注册改变数据状态(同步)
getters 用来对共享数据进行过滤并计数操作
action 解决异步改变共享数据(异步)

 

二、 创建文件:

actions.js

getters.js

index.js

mutations.js

mutation-types.js

state.js

 

三、编辑文件

这里只是拿出自己的项目来做一个例子,只是介绍封装的方法。

index.js

import Vue from ‘vue’
import Vuex from ‘vuex’
import * as actions from ‘./actions’
import * as getters from ‘./getters’
import state from ‘./state’
import mutations from ‘./mutations’
import createLogger from ‘vuex/dist/logger’ // vuex调试工具

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== ‘prodycution’ // 开发环境下开启严格模式

export default new Vuex.Store({
actions,
getters,
state,
mutations,
strict: debug,
plugins: debug ? [createLogger()] : []
})

state.js

import {playMode} from ‘common/js/config’
import {loadSearch} from ‘common/js/cache’

const state = {
singer: {},
playing: false,
fullScreen: false,
playlist: [],
sequenceList: [],
mode: playMode.sequence,
currentIndex: -1,
disc: {},
topList: {},
searchHistory: loadSearch()
}

export default state

mutations.js

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
},
[types.SET_SEARCH_HISTORY](state, history) {
state.searchHistory = history
}
}

export default mutations

mutation-types.js

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’

export const SET_SEARCH_HISTORY = ‘SET_SEARCH_HISTORY’

 

 

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119251261

posted @ 2022-05-18 20:25  忘川信使  阅读(205)  评论(0编辑  收藏  举报