vuex流程简单示例

在vue-cli中使用vuex(个人理解实现数据的公用):

1.安装vuex,在vue-cli目录下的src文件下建立vuex目录=》vuex文件夹下建立store.js文件,文件如下:
 

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

const state={
  count:1
}

const mutations={
   add(state,n){
     state.count += n;
   }
   reduce(state){
     state.count --;
  }
}

export default new Vuex.store({
    state,
    mutations
})

2,在components目录下建立Count.vue组件,代码如下

<template>
<p>{{$store.state.count}}</p>
<p>{{count}}</p>
<button @click="$store.commit(add,10)"></button>
<button @click="$store.commit(reduce)"></button>


<button @click="add"></button>
<button @click="$reduce"></button>

</template>

<script>
import store from "../vuex/store.js"
import {mapMotutions} from 'vuex'

export default{
   data(){
     return {
         msg:"学习vuex"
     }
   },
   computed:count(){
     return this.$store.state.count    //computed:mapState(['count'])
   },
   methods:{
     mapMutations(['add','reduce'])
   },         
   store
}
</script>

注:除了利用computed的计算变量来实现count,还可以了解以下vuex的mapState()简化变量的引用,mapMutation()简化方法的引用,其他诸如getter以及mapGetter()等状态的过滤使用中可以进行了解,另外action以及module等部分可以使用中理解,目前我的工作中使用对于这一块使用较少

3,认真理解其生命周期

vuex流程简单示例