VUEX學習筆記

1.創建一個js文件 ,可以全局註冊也可以在單個組件引用,我這裏創建vuex文件夾,創建store.js,我沒有全局註冊

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

//數據源
const state={
  count:1
};

//getters屬性 暫時沒用到
const getters ={
  fn:function(state){
      return state.count+=100;

  }
};


//固定寫法  修改狀態同步
const mutations ={
    add(state){
      console.log("1")
      state.count++;
    },
    reduce(state){
      state.count--;
    }
};

//修改狀態 異步   調用了mutations裏的方法
const actions = {
    addA(context){
      console.log("2")
      context.commit('add',10)
    },
    redA({commit}){
      commit('reduce',10)
    },


};

//這裏一定要記得導出
export default new Vuex.Store({
  state,getters,mutations,actions,
})

然後在需要用到這個數據的組件裏引入

  import store from '../vuex/store';
  //import { mapGetters } from 'vuex'
  export default {
    store,  //這裏一定要調用
    data(){
      return{
          msg:23,
         }

    },
    computed:{
      //...mapGetters(["fn"]),
      count1(){
         return store.state.count;
       // return this.$store.getters.count;
      }
    },

 <h3>{{$store.state.count}}</h3>  //1       先展示 接下來修改

 

  <button @click="$store.commit({type: 'add'})">點擊加1</button>
  <button @click="$store.commit('reduce')">點擊減一</button>
//這裏是調用mutations 裏的方法 



    <button @click="add2()">++++++++</button>
    <button @click="red2()">----------</button>
methods{
    adds(){
      this.$store.dispatch('addA',2)
    },
    reds(){
      this.$store.dispatch('redA')
    },
}
//這裏是 actions 裏的方法

 

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