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
this.store.getters.gettersCount訪問store.js的getters
actions:
<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>
即使用dispatch分發調用actions內的方法,再調用mutations的方法
轉載 自https://blog.csdn.net/qq_26641781/article/details/83782883