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

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

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

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

Loading…
Cancel
Save