store文件夹下,新建index.js
import Vue from 'vue'
import Vues from 'vuex'
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default
return modules
}, {})
const store = new Vuex.store({
modules
})
export default store
main.js中引入store/index.js
import store from './store/index'
new Vue({
router,
store,
render: (h) => h(App)
}).$mount('#app')
新建modules 文件夹,新建 home.js
const state = {
menuList:[],
selectedMenu: 1,
}
const getters = {
totalSum: (state) => {
return state.selectedMenu + 1
}
}
const mutations = {
updateMenuList: (state, data) => {
state.menuList= data
},
}
const actions = {
// -- 获取 菜单 list
async getMenuList({ dispatch, state, commit }, paramObj = null) {
const data = await getBubbleShowData(paramObj)
commit('updateMenuList', data)
}
}
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
1. mapState: 帮助我们映射state中的数据为计算属性,
this.$store.state.home.checkedChildTheme // home是store的module
import {mapState,mapGetters} from 'vuex'
computed: {
//借助mapState生成计算属性:selectMenu(对象写法)
...mapState({selectMenu:'selectMenu'}),
// 获取modules里的state
...mapState({
selectMenu: (state) => state.home.selectMenu
})
//借助mapState生成计算属性:selectMenu(数组写法)
...mapState(['selectMenu']),
// 获取modules里的state
...mapState('home', ['selectMenu'])
}
2.mapGetter帮助我们映射getters中的数据为计算属性:
this.$store.getters.totalSum
import {mapState,mapGetters} from 'vuex'
computed: {
//借助mapGetters生成计算属性:totalSum(对象写法)
...mapGetters({totalSum:'totalSum'}),
//借助mapGetters生成计算属性:totalSum(数组写法)
...mapGetters(['totalSum'])
},
// 原生写法
{{$store.state.name}}
3.mapActions用来生成actions对话,包含this.$store.dispatch(xxx)的函数
this.$store.dispatch('home/getMenuList', {})
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
methods:{
//靠mapActions生成:getList(对象形式)
...mapActions({getList:'getList'})
//靠mapActions生成:getList(数组形式)
...mapActions(['getList'])
// this.getList()
}
4.mapMutations帮助我们生成mutations中的方法, 即 this.$store.commit()函数
this.$store.commit('home/updateMenuList', val)
methods:{
//靠mapActions生成:updateSelectedMenu(对象形式)
...mapActions({updateSelectedMenu:'updateSelectedMenu'})
//靠mapActions生成:updateSelectedMenu(数组形式)
...mapActions(['updateSelectedMenu'])
}