VueX是Vue团队为了方便组件之间的数据共享,借鉴了redux,用来来实现vue组件全局状态(数据)管理的一种机制.
使用VueX易于开发和后期维护上都有很大的好处,
引入方式:
在下载脚手架的时候,可以选择引入,
创建仓库:
const store = new VueX.store{
}
VueX中一共有5个对象可以使用:
一、State
1.State:创建state状态,状态就是那个存数据的对象
const store=new Vuex.store({
state:{msg:"我就是所有共享的数据"}
})
2.组件中访问数据
this.$store.state.msg
二、Getter
1.Getter:类似组件中的计算属性,用来对创库数据进行计算,它会传入state对象供我们操作
const store=new Vuex.store({
state:{msg:"我就是所有共享的数据"},
getters: {
add(state){
state.msg= state.msg+"666"
}
}
})
这时,msg的数据没有被改变,只是通过计算,返回了一个其他的值
2.使用
this.$store.getters.bigMans
三、Mutation
1.设计
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
//默认传第一个参数传state
increment (state,obj) {
// 变更状态
state.count=obj.n
}
}
})
2.组件中使用
2.1 直接触发并传值(提交载荷)
this.$store.commit('increment',{n:100})
2.2 可以以一个对象的形式传入
传入对象时,当相于把整个对象作为了第二个参数传入mutations
this.$store.commit({
type: 'increment',
n:100
})
四、Action
设计
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state,obj) {
state.count=obj.n
}
},
actions: {
//默认第一个参数传一个跟store一样的对象
increment (context,obj) {
//假设fnAsync是一个异步业务函数
fnAsync(() => {
context.commit('increment',obj)
})
}
}
})
使用也是两种:
1.直接分发
this.$store.dispatch('increment',{n:100})
//2.以对象形式分发
this.$store.dispatch({
type: 'increment',
n:100
})
Module
可用于业务分块开发: 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter
这样便于团队的开发和后期维护。