Vuex 学习与简单使用

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

主要用来管理某种状态(包括更改某个状态状态),对于多层嵌套路由间的传参特别有效

此处以分割各个部分来记录,以便后续参照使用

在src 文件夹中新建store文件夹

store文件夹里分别新建以下文件:

    index.js:我们组装模块并导出 store 的地方
    state.js:状态变量
    getters.js:将state中的状态暴露出去,以便其他组件使用
    actions.js:异步方法
    mutations.js:更改状态的方法

    types.js:记录自己的操作对应表(不是必须,只是为了方便后续查阅)

以官方的简单计数为例:

    state.js 文件如下:

const state = {
  count:20
};
export default state;

 getters.js 文件如下:  

import state from "./state";
const getters = {
  count: state => {
    return state.count;
  }
};
export default getters;

types.js 文件如下:

export const INCREMENT = "increment";//作 + 运算
actions.js 文件如下:
import * as types from "./types";
const actions = {
  /*******
   * 带参数写法
  [types.INCREMENT]: ({ commit },params) => {
    commit(types.INCREMENT,params);
  }
   *********** */
  [types.INCREMENT]: ({ commit }) => {
    commit(types.INCREMENT);
  }
};
export default actions;

mutation.js 文件如下:

import * as types from "./types";
import state from "./state";
const mutations = {
  /********
   * 带参数
  [types.INCREMENT](state,params){
    state.count+=params;
  }
   * ************** */
  [types.INCREMENT](state){
    state.count++;
  }
};
export default mutations;

index.js 文件如下:

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
import state from "./state";
import actions from "./actions";
import mutations from "./mutations";
import getters from "./getters";
const store = new Vuex.Store({
  state,
  actions,
  getters,
  mutations
});
export default store;

后续若要管理其他状态,通过某个方法更改状态,在对应的文件中,以类似的方式增加相应代码即可

在组建中使用:具体使用请查阅官方文档:点击打开链接  此处记录个人认为最简单最后用的方法

首先在组件导入:mapGetters,mapActions,详细解释清参照官方文档:点击打开链接

import {mapGetters,mapActions} from "vuex"

在computed中:

computed:{
    ...mapGetters(['count'])
  },

在methods中:

methods{
    ...mapActions(['increment'])
  },

可以直接在模板中使用:

<p>{{count}}</p>
<button @click="increment">自增</button>

也可以在mounted中通过dispatch调用action:

mounted(){
   this.$store.dispatch("increment");
  },
注意:
使用前要进行安装,安装方法为:cnpm install vuex -D

在main.js 要导入store并在VUE实例中进行使用

import store from "./store";
new Vue({
  el: "#app",
  router,
  store,
  render: h => h(App)
});

猜你喜欢

转载自blog.csdn.net/qq_36111804/article/details/81017216