完成vuex中的getters,mapState,mapGetters,mapActions和mapMutations的学习

new_branch1
roger 2 years ago
parent 58b5ae9e08
commit ce0122a287
  1. 39
      20_脚手架/vue_code/src/components/Count.vue
  2. 12
      20_脚手架/vue_code/src/store/index.js

@ -1,19 +1,23 @@
<template>
<div>
<h1>当前求和为: {{$store.state.sum}}</h1>
<h1>当前求和为: {{ sum }}</h1>
<h3>当前求和放大10倍后为: {{ bigSum }}</h3>
<h3>我在{{ school }}{{ subject }}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add">+</button>
<button @click="sub">-</button>
<button @click="addOdd">当前求和为奇数再加</button>
<button @click="addWait">等一等再加</button>
<button @click="add(n)">+</button>
<button @click="sub(n)">-</button>
<button @click="addOdd(n)">当前求和为奇数再加</button>
<button @click="addWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState, mapGetters, mapMutations, mapActions} from "vuex";
export default {
name: "Count",
data() {
@ -24,24 +28,25 @@ export default {
mounted() {
console.log('Count', this)
},
methods: {
add() {
this.$store.commit('vuexAdd', this.n)
},
sub() {
this.$store.commit('vuexSub', this.n)
},
addOdd() {
this.$store.dispatch('vuexAddOdd', this.n)
...mapMutations({add:'vuexAdd', sub:'vuexSub'}), //
// ...mapMutations(['vuexAdd', 'vuexSub']), //
...mapActions({addOdd:'vuexAddOdd', addWait:'vuexAddWait'}),
},
addWait() {
this.$store.dispatch('vuexAddWait', this.n)
}
computed: {
...mapState(['sum', 'school', 'subject']), //
// ...mapState({sum: 'sum', school: 'school', subject: 'subject'}), //
...mapGetters({bigSum: 'bigSum'})
}
}
</script>
<style>
button {margin-left: 5px}
button {
margin-left: 5px
}
</style>

@ -32,7 +32,16 @@ const mutations = {
}
//准备state-用于存储数据
const state = {
sum: 0
sum: 0,
school: '修仙学院',
subject: '修仙'
}
// getters 用于对state中的数据进行加工,类似用computed
const getters = {
bigSum(state) {
return state.sum * 10
}
}
// 创建并导出store
@ -40,4 +49,5 @@ export default new Vuex.Store({
actions,
mutations,
state,
getters
})

Loading…
Cancel
Save