1.state
作用:
保存公共数据
格式:
state() {return {属性名: 属性值 }}
使用:
组件中
this.$store.state.属性名
模板中
{{$store.state.属性名}}
2.mutations
作用:
调用mutations来修改定义在state中的公共数据
格式:
mutations:{
mutation名(state [, 形参]) {
执行函数
}
使用:
this.$store.commit('mutation名', 实参)
参数说明:
第一个参数是必须的,表示当前的state。在使用时不需要传入
第二个参数是可选的,表示载荷,是可选的。在使用时要传入的数据
3.getters
作用:
对数据进行加工得到新数据(等价于computed)
格式:
getters: {
// state 就是上边定义的公共数据state
getter的名字:(state)=>{
执行函数
return 要返回的值}
}
使用:
$store.getters.getter的名字
4.actions
作用:
发异步请求获取数据,调用mutations来保存数据,将整个ajax操作封装到Vuex的内部
格式:
actions: {
// context对象会自动传入,它与store实例具有相同的方法和属性
async action的名字: function(context, 载荷) {
// 1.发送异步请求并将请求回来的数据存起来
const res =await axios.get('路径')
// 2.调用context.commit('mutation名', 载荷)
context.commit('mutations中函数名',res.data.data)
}
使用:
this.$store.dispatch('actions的名字', 参数)
5.modules
作用:
拆分模板,把复杂的场景按模块来拆开
格式:
modules: {
模块名1: {
// namespaced为true,则在使用属性时,就必须要加上模块名
namespaced: true,
state: {},
getters: {},
mutations: {},
actions: {},
modules: {}
},
}
使用:
获取数据项: {{$store.state.模块名.数据项名}}
获取getters: {{$store.getters['模块名/getters名']}}
...
扩展:
6.vuex-map辅助函数
用法:
1. 导入(用到那个属性导入哪个属性)
import { mapState,mapMutations,mapGetters,mapActions } from 'vuex'
2.调用
2.1 单纯的使用
...map工具函数(['xxx1','xxx2']) //xxx为你要用的数据或函数
2.2 需要改名字
...map工具函数({'新名字':xxx1'})
2.3 modules中的数据
...map工具函数('模块名', ['xxx'])
...map工具函数('模块名',{'新名字':'xxx1'})
注意点:
computed中使用 mapState mapGetters
methods中使用 mapMutations mapActions
两者的执行流程
总结
(画得不好)