五大核心
1.state: 统一定义公共数据(类似于data)
(1) 如何使用全局state
1.直接使用: $store.state.属性名 (this.$store.state.属性名)
2.map辅助函数:
在组件中按需导入mapState
import {mapState} from "vuex"
在计算属性中添加你要使用的state属性
computed: {
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
(2)如何使用模块中的state
1.直接使用: $store.state.模块名.属性名 (this.$store.state.模块名.属性名)
2.map辅助函数:
在组件中按需导入mapState
import {mapState} from "vuex"
computed: {
...mapState('模块名', ['xxx']),
...mapState('模块名', {'新名字': 'xxx'})
}
2.mutations : 使用它来修改数据(类似于methods)
(1)如何使用全局mutations
1.直接使用: $store.commit('mutations名', 参数)
2.map辅助函数:
在组件中按需导入mapMutations
import {mapMutations} from "vuex"
methods: {
...mapMutations(['mutation名']),
...mapMutations({'新名字': 'mutation名'})
}
(2)如何使用modules中的mutations(namespaced:true)
1.直接使用: $store.commit('模块名/mutations名', 参数)
2.map辅助函数:
在组件中按需导入mapMutations
import {mapMutations} from "vuex"
methods: {
...mapMutations('模块名', ['xxx']),
...mapMutations('模块名',{'新名字': 'xxx'})
}
3. getters: 类似于computed(计算属性,对现有的状态进行计算得到新的数据-------派生 )
(1)如何使用全局getters
1.直接使用: $store.getters.getter名
2.map辅助函数:
在组件中按需导入mapGetters
import {mapGetters} from "vuex"
computed: {
...mapGetters(['getter名']),
...mapGetters({'新名字': 'getter名'})
}
(2) 如何使用modules中的getters
1.直接使用: $store.getters.模块名.getter名
2.map辅助函数:
computed: {
...mapGetters('模块名', ['getter名']),
...mapGetters('模块名',{'新名字': 'getter名'})
}
4. actions: 发起异步请求
(1)如何使用全局actions
1.直接使用: $store.dispatch('actions名', 参数)
2.map辅助函数:
在组件中按需导入mapActions
import {mapActions} from "vuex"
methods: {
...mapActions(['actions名']),
...mapActions({'新名字': 'actions名'})
}
(2) 如何使用modules中的getters
1.直接使用: $store.dispatch('模块名/actions名', 参数)
2.map辅助函数:
methods: {
...mapGetters('模块名', ['actions名']),
...mapGetters('模块名',{'新名字': 'actions名'})
}
5. modules: 模块拆分
(1) modules的作用:拆分模板,把复杂的场景按模块来拆开
(2) 在使用modules时,建议都给加上namespaced! 使用了modules之后,在访 问数据时就要额外添加modules的名字了。
小结
1.actions和mutations和state的关系图
2.全部关系图