vue.js---前端状态管理

2019-08-14  本文已影响0人  学的会的前端

Vuex之store

npm install vuex

第一步:引入vuex,并通过use方法使用它

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

第二步: 创建状态仓库

//定义咋main.js
//创建状态仓库,注意Store,state不能改
var store = new Vuex.Store({
  state:{
    XXX:xxx
  }
})
//直接通过this.$sore.state.XXX拿到全局状态

第三步:通过this.$sore.state.XXX直接拿到需要的数据

Vuex的相关操作

  1. 方法1
//创建状态仓库,注意Store,state不能改
var store = new Vuex.Store({
  state:{
    XXX:xxx
  },
  mutations:{
  //改变状态
  }
})
this.$store.commit(XXX);
此处的XXX是你在mucations中定义的方法名


//具体代码实现

var store = new Vuex.Store({
  state: {
    num: 88
  },
  mutations: {
    //定义状态改变函数
    increase:function(state){
      state.num ++;
    },
    //ES6写法
    decrease(state){
      state.num --;
    }
  }
})
  1. 方法2
    注意:actions提交的是mutation,而不是直接变更状态
    actions可以包含异步操作,但是mutation只能包含同步操作
var store = new Vuex.Store({
  state:{
    XXX:xxx
  },
  mucations:{
    a:function(state){
    }    
  },
  actions:{
    //context上下文对象
    b:function(context){
    //commit中的参数只能是mucations中的函数
    //因为actions只能对mucations进行操作。
    //方法必须现在mucations中定义,才能在actions中起作用
      context.commit('a');
    }
  }
})
如何调用
this.$store.dispatch(XXX);


//具体代码示例:
 actions: {
      //context上下文对象
      decreaseAction: function(context){
        //actions中只能对mutation进行操作
        context.commit('decrease')
      }
    },
getters:{
  //对状态进行处理
}
//获取数据
this.$store.getters.getCount

//具体代码示例
getters: {
      //很多时候是从getters中定义的方法获取状态
      getNum(state){
        return state.num > 0 ? state.num : 0
      }
    }
上一篇 下一篇

猜你喜欢

热点阅读