Vuex是一个专门为Vue.js应用程序开发的状态管理模式,采用集中存储来管理数据,是一个单独的全局化管理模式
1.下载vuex
npm i vuex
2.导出
在src目录下创建store/index.js
index.js
import Vuex from 'vuex'
注册
import Vue from 'vue'
Vue.use(Vuex)
实例化
const store =new Vuex.Store({
state:{
// 共享的数值
},
mutations:{
},
actions:{
},
getters:{
}
})
暴露出去 export default store
3.导入
在main.js中导入并且挂载到vue上
import store from '@/store'
new Vue({
store
})
这样就设置好了一个全局的仓库,可以将数据保存到仓库中
——各种获取数据方法
在vuex中,获取数据分为:
- 直接获取根仓库数据
- 获取模块数据
直接获取
直接获取可以通过定位仓库获取和使用辅助函数获取
直接获取仓库内的数据 | |
state | this.$store.state.数据名 |
mutations | this.$store.commit.方法名 |
actions | this.$store.dispatch.方法名 |
getters | this.$store.getters.方法名 |
在vuex中封装了辅助函数方便我们进行调用仓库内的数据,它通过映射器来反馈出仓库内的数据,这个映射需要将辅助函数展开后才能使用,当直接调用时接收一个数组,这个数组内的值就是需要调用的数据或者方法.
获取模块内的数据
获取数据之前需要先创建模块
在store文件夹内新建一个modules文件夹然后创建一个模块js文件,模块内的布局与index.js相同
const state = {}
const mutations = {}
const getters = {}
const actions = {}
export default {
namespaced: true,
state: state,
mutations: mutations,
actions: actions,
getters: getters
}
namespaced命名空间默认为false,当它为true时想要访问模块必须加上模块名
获取模块内的数据 | |
state | this.$store.state.模块名.数据名 |
mutations | this.$store.commit('模块名/方法名') |
actions | this.$store.dispatch('模块名/方法名') |
getters | this.$store.getters['模块名/方法名'] |
因为state本身已经具有命名空间所以不受影响直接嵌套
辅助函数
辅助函数一共有四个
- mapState
- mapMutations
- mapActions
- mapGetters
注意:所有的辅助函数映射时都需要使用展开运算符展开
辅助函数
//在组件中导入mapstate辅助函数
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
computed: {
...mapState('模块名', ['数据名']),
...mapGetters('模块名', ['方法名'])
},
methods: {
...mapActions('模块名', ['方法名']),
...mapMutations('模块名', ['方法名'])
},
//调用就相当于直接在组件内调用
模块内actions详细写法
actions 属性中有六个参数
调用
store.state
store.rootState
store.commit
store.dispatch
store.getters
store.rootGetters
//store内有六个参数
actions:{
方法名(store){
store:{
state:当前模块的state数据,
rootState:根模块下的state数据
rootState.模块名.属性名
commit:调用mutations方法
调用本模块的mutations方法: commit('本模块的mutations方法名',实参值)
调用其它模块的mutations方法:commit('模块名/方法名',实参值(没有用null点位),{root:true})
dispatch:调用actions方法
调用本模块actions方法:dispatch('本模块的actions方法',实参)
调用其它模块的actions方法:dispatch('模块名/方法名',实参(没有用null占位),{root:true})
getters:调用getters方法
getters.本模块的getters方法名
rootGetters:调用根模块下的getters方法
调用其它模块的getters:rootGetters['模块名/其它模块getters方法']
}
}
}
getters完整写法
类似于actions
getters:{
方法名(state,getters,rootState,rootGetters){
state:当前模块的state数据,
rootState:根模块下的state数据
rootState.模块名.属性名
getters:调用getters方法
getters.本模块的getters方法名
rootGetters:调用根模块下的getters方法
调用其它模块的getters:rootGetters['模块名/其它模块getters方法']
}
}
},