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,認真理解其生命週期

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章