-
state:vuex的基本数据,用来存储变量
-
geeter:从基本数据(state)派生的数据,相当于state的计算属性
-
mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,提交载荷作为第二个参数。
-
action:和mutation的功能大致相同,不同之处在于 ==》1. Action 提交的是 mutation,而不是直接变更状态。 2. Action 可以包含任意异步操作。
-
modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。
设置值
import Vue from ‘vue’
import Vuex from ‘vuex’
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//存入数据
ct: 0
},
mutations: {
//修改数据,只有mutation能修改数据
//state 是传的参数
add (state) {
state.ct++
},
addn (state, step) {
state.ct += step
},
jian (state) {
state.ct–
},
jiann (state, step) {
state.ct -= step
}
},
actions: {
//action是通过mutation来修改数据的,
是修改异步操作的
// context 可以看成Store实例
addasync (context) {
setTimeout(() => {
context.commit(‘add’)
}, 2000)
},
addnasync (context, step) {
setTimeout(() => {
context.commit(‘addn’, step)
}, 2000)
},
subacync (context) {
setTimeout(() => {
context.commit(‘jian’)
}, 2000)
}
},
getters: {
//相当于计算属性,用于修改state形成新的数据,state修改getters会跟着一起修改,不会影响原来的state数据
xinshu (state) {
return 当前最新数据为${state.ct}
}
},
modules: {
}
})
使用
1 使用点语法
1this.store.state.‘数据名’2this.store.state.‘数据名’
2 this.store.state.‘数据名’2this.store.commit.‘mutation数据名’
3this.store.dispatch.‘action数据名’4this.store.dispatch.‘action数据名’
4this.store.dispatch.‘action数据名’4this.store.state.‘getters数据名’
只有commit 和 dispatch才能触发各自的属性修改数据
2映射到计算属性或methods里面,再通过插值表达式引入即行
先引入import { mapState’,mapMutations, mapActions, mapGetters } from 'vuex基本就是map加属性名
然后隐射
…mapState([‘数据名’])
…mapMutations([‘mutation数据名’, ‘jiann’]),
…mapActions([‘action数据名’]),
…mapGetters([‘getters数据名’])
同步操作和异步操作数据是在计算属性中进行映射
下面是上面的代码的使用
传参就是在使用的时候在方法传参,同理,属性内页需要一个接受参数的变量