安装
npm install vuex@next --save
# vuex-demo/src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')
# vuex-demo/src/store/index.js
import { createStore } from 'vuex'
export default createStore({
state: {
count:0
},
getters: {
showNum: state => {
return '当前最新的数量是:【'+ state.count +'】'
}
},
mutations: {
add(state) {
state.count++
},
addN(state,step) {
state.count += step
}
},
actions: {
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000)
},
addNAsync(context,step) {
setTimeout(() => {
context.commit('addN',step)
}, 1000)
}
},
modules: {}
})
State —— 公共数据
<template>
<div>{{this.$store.state.count}}</div>
</template>
<template>
<div>{{count}}</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['count'])
}
};
</script>
Getter —— 包装数据
<template>
<div>{{this.$store.getters.showNum}}</div>
</template>
<template>
<div>{{showNum}}</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['showNum'])
}
};
</script>
Mutations —— 改变数据
<template>
<button @click="add1">+1</button>
<button @click="add3">+3</button>
</template>
<script>
export default {
methods: {
add1() {
this.$store.commit('add')
},
add3() {
this.$store.commit('addN',3)
},
}
};
</script>
<template>
<button @click="sub">+1</button>
<button @click="subN(3)">+3</button>
</template>
<script>
import { mapMutations} from 'vuex'
export default {
methods: {
...mapMutations(['sub','subN'])
}
};
</script>
Action —— 异步操作
<template>
<button @click="add1">+1</button>
<button @click="add3">+3</button>
</template>
<script>
export default {
methods: {
add1() {
this.$store.dispatch('addAsync')
},
add3() {
this.$store.dispatch('addNAsync',3)
}
}
};
</script>
<template>
<button @click="addAsync">+1</button>
<button @click="addNAsync(3)">+3</button>
</template>
<script>
import { mapActions} from 'vuex'
export default {
methods: {
...mapActions(['subAsync','subNAsync'])
}
};
</script>