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 里的方法

 

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