单独安装vuex:npm i vuex
创建store仓库创建index.js模块(store/index.js)
import Vue from 'vue' //引入核心库
import Vuex from 'vuex' //引入vuex 核心插件
Vue.use(Vuex) //调用vuex插件
//情景1:
import state from './state';
import actions from './actions';
import getters from './getters';
import mutations from './mutations';
import mo1 from '../store/modules/mo1';
import mo2 from '../store/modules/mo2';
export default new Vuex.Store({
state,
mutations,
getters,
actions,
modules: {
mo1,mo2
}
})
//情景2(modules文件夹里有很多的文件,这里多了一个方法取出里面的modules模块文件):
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,
getters
})
export default store
Vuex(包含store库和映射函数)===>
new Vuex.Store实例对象 ====》
情景1:情景2:
创建modules下的单个js仓库文件(store/modules/mo1.js)
modules解决state数据臃肿问题,把仓库切割成不同的模块
const state = {
title: title
}
const mutations = {
CHANGE_SETTING: (state, data) => {
state.title=data
}
}
const actions = {
changeSetting({ commit }, data) {
commit('CHANGE_SETTING', data)
}
}
const getters ={
getTitle:state=>state.title
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
把封装好的仓库模块 注入到vue实例上(main.js)
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
辅助性函数(映射函数)--减少代码量+命名空间--增加可读性
因为Vuex(包含store库和映射函数)所以:import { mapGetters,mapState } from 'vuex'
因为映射函数本身就是一个函数 所以:...mapState([ 'title', ])后title直接可以使用
基础使用:
//因为store已经挂载到了vue上,所以可以直接使用this.$store
this.$store.state.title
this.$store.getters.getTitle
this.$store.mutation('type',data)
this.$store.dispatch('type',data)
命名空间+辅助性函数
<template>
<div>
mapState---- {
{name}}
mapGetters ----{
{getName}}
----------{
{this.$store.getters['mo1/getName']}}
</div>
</template>
import { mapGetters,mapState,mapActions } from 'vuex'
computed:{
//使用命名空间,这种只能使用对象方式重新命名,mo1是某个modules的模块js文件(mpaState不能使用这种)
//未使用辅助函数+命名空间
this.$store.getters['mo1/getName']
// 【辅助函数+命名空间方式一】获取store中的数据(代码更简洁)
...mapState(['name']),
...mapState({ proData: state => state.productModule.proData }),
...mapGetters(['getName','themeModule/themeData'])
// 【辅助函数+命名空间方式二】获取store中的数据(代码最简洁)
// 将模块的空间名称字符串作为第一个参数传递给辅助函数,这样所有绑定都会自动将该模块作为上下文。
...mapState('mo1', { proData: state => state.proData }),
...mapGetters('mo1', ['getName','themeData']),
...mapGetters({getName: 'mo1/getName'})
},
created(){
this.titleFun(data);
this.fun(data)
},
methods:{
//未使用辅助函数+命名空间
fun(data){
this.$store.dispatch('mo1/titleFun', data)
}
// 【辅助函数+命名空间
...mapActions(['titleFun',data]);
...mapActions('mo1',['titleFun',data])
}
命名空间
模块具有更高的封装度和复用性,添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名