# vuex
import Vue from "vue";
import Vuex from "vuex";
import Cookies from 'js-cookie'
Vue.use(Vuex);
// 数据源
let state={
rwbh:0,
count:0,
num:0
}
// Action 提交的是 mutation,而不是直接变更状态
let mutations ={
add(state){
state.rwbh++
},
adds(state,step){
state.count += step
}
}
// 响应在 view 上的用户输入导致的状态变化
let actions ={
addAsync(contest){
setTemout(()=>{
//mutations的方法commit
contest.commit('add')
},1000)
},
addsAsync(contest,step){
setTemout(()=>{
//mutations的方法commit
contest.commit('adds',step)
},1000)
}
}
// getters 可以对State进行计算操作
let getters ={
//缩写
showNum:state =>{
return '当前最新数量【'+ state.num +'】'
}
showNum(state){
return '当前最新数量【'+ state.num +'】'
}
}
// 暴露模块
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
# state 数据
state 方法1 state
import store from "../../store";
this.$store.state.rwbh
state 方法2 mapState
<div>{{ rwbh }}</div>
import {mapState} from 'vuex'
computed:{
...mapState(['rwbh'])
}
gitlist(){
this.rwbh
}
# Mutation 方法
Mutation 方法1 commit
(不要Mutation 执行异步操作)
import store from "../../store";
this.$store.commit('add')
this.$store.commit('adds',3)
Mutation 方法2 mapMutations
(不要Mutation 执行异步操作)
<div @click="onclick()"> 点击 </div>
<div @click="add"> 点击 </div> //直接调用
import {mapState, mapMutations } from 'vuex'
computed:{
...mapState(['rwbh','count'])
}
methods:{
...mapMutations(['add','adds'])
onclick(){
this.add()
this.adds(3)
}
}
# Actions 异步方法 (异步操作)
Actions 方法1 dispatch
import store from "../../store";
this.$store.dispatch('addAsync')
this.$store.dispatch('addsAsync',5)
Actions 方法2 mapActions
<div @click="onclick()"> 点击 </div>
<div @click="handler()"> 异步点击 </div>
<div @click="addAsyn"> 异步点击 </div> //直接调用
import {mapState, mapMutations,mapActions } from 'vuex'
computed:{
...mapState(['rwbh','count'])
}
methods:{
...mapMutations(['add','adds'])
...mapActions('addAsync','addsAsync')
onclick(){
this.add()
this.adds(3)
}
handler(){
this.addAsync()
this.addsAsync(3)
}
}
# Getter 计算
getter 方法1 getters
import store from "../../store";
this.$store.getters('showNum')
getter 方法2 mapGetters
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum'])
}
# Module 模块
全局模块
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
局部模块
const moduleA = {
state: () => ({
count: 0
}),
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}