vuex 解决了组件以及路由之间相互通讯和实时更新的问题
1. State
state 提供统一公告资源,所有公共的变量可以放在 state 中存储
// 声明全局变量
const store = new Vuex.Store({
state: { count: 0 }
})
/**
* 调用全局变量
* 方法一: this.$store.state 调用
*/
this.$store.state.count // this 指向全局 vue 实例
/**
* 方法二: mapState API
*/
import { mapState } from 'vuex'
computed: {
...mapState(['count'])
}
2. Mutation
Mutation 用来修改 state 中的值,注意,不能直接修改 state 中的值,需要调用 Mutation
// 声明全局变量 以及对应 Mutatiaon
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, data) {
// 可以通过 state 取到变量的值
// data 是传递的参数
state.count = data
}
},
})
// 触发方法
this.$store.commit('count', 1)
// mapMutations API
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add']),
vuexAdd () {
// 直接调用并传参即可
this.add(1)
}
}
2. Mutation
Mutation 用来修改 state 中的值,注意,不能直接修改 state 中的值,需要调用 Mutation
// 声明全局变量 以及对应 Mutatiaon
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, data) {
// 可以通过 state 取到变量的值
// data 是传递的参数
state.count = data
}
},
})
// 触发方法一
this.$store.commit('count', 1)
// 触发方法二
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add']),
vuexAdd () {
// 直接调用并传参即可
this.add(1)
}
}
注意: 此方法中不能有异步操作
3. Action
Action 用于解决 Mutation 中的异步操作
// 声明全局变量 以及对应 Mutatiaon、Action
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, data) { state.count = data }
},
actions: {
addAsync (context, step) {
setTimeout(() => {
// 通过调用 mutations 中定义的方法,来实现异步修改 state
context.commit('add', step)
}, 1000)
}
}
})
// 触发方法一
this.$store.dispatch('addAsync', 1)
// 触发方法二
import { mapActions } from 'vuex'
methods: {
...mapActions(['addAsync']),
vuexAdd () {
// 直接调用并传参即可
this.addAsync('add', 1)
}
}
4. Getter
Getter 可以讲 state 中的变量,包装成新的数据形式
// 声明全局变量 以及对应 Getter
const store = new Vuex.Store({
state: { count: 0 },
Getter: {
showCount(state) {
return '当前的最新 count 是' + state.count
}
}
})
// 获取方法一
this.$store.getters.showCount
// 获取方法二
import { mapGetters } from 'vuex'
computed: {
...mapGetters (['showCount']),
}