Vuex的使用方法mutation和action及getter的基本使用


mutations
在vue 中,只有mutation 才能改变state.  mutation 类似事件,每一个mutation都有一个类型和一个处理函数,因为只有mutation 才能改变state, 所以处理函数自动会获得一个默认参数 state. 所谓的类型其实就是名字,

先看上一篇文章的例子:

在没有用vuex的时候,我们可以实现点击颜色切换

用了vuex后,只实现了颜色变换一次的功能,那我们可不可以变换很多次呢?

mutations 登场 , 问题迎刃而解 :

store.js:

  1.   import Vue from 'vue';
  2.   import Vuex from 'vuex';
  3.   Vue.use(Vuex);
  4.   const state = {
  5.       show:false
  6.   }
  7.   export default new Vuex.Store({
  8.       state,
  9.       mutations:{
  10.           switch_color(state){
  11.               state.show = state.show?false:true
  12.           }
  13.       }
  14.   })
  15.   父组件: 
  16.    
  17.  
  18.   <script>
  19.       import children from "@/components/children"
  20.       export default {
  21.           components: {
  22.               children
  23.           }
  24.       }
  25.   script>


使用$store.commit('switch_color') 来触发 mutations 中的 switch_color 方法。

再举个例子
1、现在我们store.js文件里增加一个常量对象。store.js文件就是我们在引入vuex时的那个文件

const state = { count:1 }

2、用export default 封装代码,让外部可以引用

export default new Vuex.Store({undefined

    state

  });

store.js:

  1.   import Vue from 'vue';
  2.   import Vuex from 'vuex';
  3.   Vue.use(Vuex);
  4.   const state = {
  5.       count:1
  6.   }
  7.   export default new Vuex.Store({
  8.       state,
  9.       mutations:{
  10.           add(state){
  11.               state.count += 1;
  12.           },
  13.           reduce(state){
  14.               state.count -= 1;
  15.           }
  16.       }
  17.   })


新建一个vue的模板,位置在components文件夹下,名字叫page.vue。在模板中我们引入我们刚建的store.js文件,并在模板中用{undefined{$store.state.count}}输出count 的值。

  1.