一般在大型的项目中,通常会用到vuex来管理,那么vuex到底是什么呢?
一、什么是vuex
- 官方文档解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
- 简单来说,一般在大型的项目中,如果有多个组件之间传值,频繁的调用使用组件传值会使数据变得不好管理。为此vue提供了一个可以统一管理的工具—vuex,可以把这些组件所使用的值存放在一个集中的地方,方便统一管理与调用。
二、vuex的使用
官网给出的vuex的使用示例图
state
----Vuex 使用单一状态树,就是保存所有数据的状态,相当于vue实例中的data
const store = new Vuex.Store({
state: {
datalist: []
}
})
可以使用辅助函数**mapState**获取vuex中state里的数据状态
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed:{
//这种写法不仅可以使用辅助函数,还可以定义写一些其他的方法
...mapState(['datalist'])
},
//官网写法
//computed:mapState({
// //定义别名
// mydatalist:state=>state.datalist
// })
}
mutations
----改变state中数据状态的唯一方法是提交 mutation,也就是通过mutations里的函数更改,调用mutations里的函数使用store.commit(‘函数名’)
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
使用store.commit()方法调用调用此函数
store.commit('increment')
可以使用辅助函数**mapMutations**将组件中的 methods 映射为 store.commit 调用
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapMutations } from 'vuex'
export default {
methods:{
//获取mutations中的方法
...mapMutations(['DEL'])
//调用该方法
this.DEL(id)//也可以直接在组件中使用 DEL(id)直接绑定click事件
},
}
actions
------如果调用后端接口进行异步操作时,就需要通过actions来改变mutations里的方法,Action 类似于 mutation,不同在于:Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
调用acitions使用store.dispatch()方法来触发
store.dispatch('increment')
可以使用辅助函数**mapActions**将组件的 methods 映射为 store.dispatch 调用
import { mapActions } from 'vuex'
export default {
// ...
methods: {
// 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
...mapActions([ 'increment'])
}
gettters
----Getter相当于vue中的computed计算属性
getters:{
pages(state){
return Math.ceil(state.datalist.length/3)
}
},
可以使用辅助函数 **mapGetters**获取到vuex中的计算属性的值
import {mapGetters} from 'vuex'
export default {
computed:{
...mapGetters(['pages'])
},
}
modules
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {
namespaced:true,
state:{
num:100
},
mutations:{
ADDNUM(state){
state.num++
}
}
actions: { ... },
getters: { ... }
}
const moduleB = {
state: {
name:'dny'
},
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
moduleA,
moduleB
}
})
在组件中使用vuex,使用$store.state+模块名访问vuex模块的状态属性,如果需要调用模块中mutations中的方法,最好使用命名空间来区分每个模块里的方法
<template>
<div>
num:{{$store.state.moduleA .num}}
name:{{$store.state.moduleB .name}}
<!-- 命名空间 方法前面加引入模块的key的名字 -->
<button @click='$store.commit("Cart/ADDNUM")'>点击</button>
</div>
</template>