1. vue中只有通过mutations去改变状态的时候,才会有一个状态记录

一、mapMutations

通过这个方法可以在组件中使用vuex中mutations属性中的方法

demo实现一个跨页面的计数器

1-1 常规方法的实现

  1. <template>
  2. <div class="about">
  3. <h1>{{this.$store.state.count}}</h1>
  4. <button @click="increase">增加</button>
  5. <button @click="decrease">减少</button>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. methods:{
  11. increment(){
  12. this.$store.commit("increase")
  13. },
  14. decrement(){
  15. this.$store.commit("decrease")
  16. }
  17. }
  18. }
  19. </script>
  1. //vuex
  2. export default new Vuex.Store({
  3. state: {
  4. count:0
  5. },
  6. mutations: {
  7. increase(state){
  8. state.count+=1;
  9. },
  10. decrease(state){
  11. state.count-=1;
  12. }
  13. }
  14. })

1-2 使用mapMutations

  1. <template>
  2. <div class="about">
  3. <h1>{{this.$store.state.count}}</h1>
  4. <button @click="increase">增加</button>
  5. <button @click="decrease">减少</button>
  6. </div>
  7. </template>
  8. <script>
  9. import {mapMutations} from 'vuex';
  10. export default {
  11. methods:{
  12. ...mapMutations(['increase','decrease'])
  13. }
  14. }
  15. </script>

1-3和上面方法类似

  1. <template>
  2. <div class="about">
  3. <h1>{{this.$store.state.count}}</h1>
  4. <button @click="add">增加</button>
  5. <button @click="reduce">减少</button>
  6. </div>
  7. </template>
  8. <script>
  9. import {mapMutations} from 'vuex';
  10. export default {
  11. methods:{
  12. ...mapMutations(['increase','decrease']),
  13. add(){
  14. this.increase()
  15. },
  16. reduce(){
  17. this.decrease()
  18. }
  19. }
  20. }
  21. </script>

二、mapActions

  1. export default new Vuex.Store({
  2. state: {
  3. count:0
  4. },
  5. mutations: {
  6. increase(state){
  7. state.count+=1;
  8. },
  9. decrease(state){
  10. state.count-=1;
  11. }
  12. },
  13. actions: {
  14. myIncrease(ctx){
  15. ctx.commit("increase")
  16. },
  17. myDecrease(ctx){
  18. ctx.commit("decrease")
  19. }
  20. }
  21. })
  1. <template>
  2. <div class="about">
  3. <h1>{{this.$store.state.count}}</h1>
  4. <button @click="add">增加</button>
  5. <button @click="reduce">减少</button>
  6. </div>
  7. </template>
  8. <script>
  9. import {mapActions} from 'vuex';
  10. export default {
  11. methods:{
  12. ...mapActions(['myIncrease','myDecrease']),
  13. add(){
  14. this.myIncrease()
  15. },
  16. reduce(){
  17. this.myDecrease()
  18. }
  19. }
  20. }
  21. </script>