继前文《Vue之Vuex(状态管理模式)》,在store.js添加getters和actions方法:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store =  new Vuex.Store({
  state:{
    count:1
  },
  mutations:{
    increment(state){
      state.count++
    }
  },
  getters:{
    gettersCount(state){
      return state.count * 2
    }
  },
  actions:{
    actionsCount(context){
      //调用mutations的自增方法
      context.commit('increment')
    }
  }
})

export default store

在About.vue访问新增的方法,this. s t o r e . g e t t e r s . g e t t e r s C o u n t 访 问 s t o r e . j s 的 g e t t e r s , t h i s . store.getters.gettersCount访问store.js的getters, this. store.getters.gettersCount访store.jsgettersthis.store.dispatch(‘actionsCount’)调用store.js的actions定义好的actionsCount,先访问actionsCount,在实现mutations里的自增方法:

<template>
  <div class="about">
    这是about组件
    <br>
    <br>
    <br>
    <br>
    <!-- 3.引用store的count -->
    {{this.$store.state.count}}---{{this.$store.getters.gettersCount}}
    <button  @click="incre">累加</button>
  </div>
</template>

<script>
//1.引入store
import store from "../store.js"
export default {
  data(){
    return{
      title:"这是about组件"
    }
  },
  //2.注册
  store,
  methods:{
    incre(){
      //改变值的话,引用store.js的increment方法
      //this.$store.commit("increment")
      this.$store.dispatch('actionsCount')
    }
  }
}
</script>
Logo

前往低代码交流专区

更多推荐