vuex是什么?怎么用,例子

什么是vuex?

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

为什么要用vuex?

  • 对于父子组件之前的通信,父组件通过porps传递到子组件,子组件通过$emit发送事件到父组件;父组件还可以通过ref的方式拿子组件的值并共享;

  • 对于组件与组件之间的通信,可以new一个新的Vue实例,专门用来做event bus进行通信。怎么用?

  • 当多个组件之间共享一个状态时,event bus可能就变成乱了

怎么用?

  组件A的js中:  this.$store.dispatch('get_beforeVote_params',this.dynamicValidateForm.email);            //设值

  组件B的template中:<p>{{'beforeVoteParams:'+$store.state.vote.beforeVoteParams}}</p>                   //引用值

  组件B的js中:   如果没有引用这句话:import store from '@/store/index'         就:this.$store.state.vote.beforeVoteParams 直接用;

          如果引用了这句话:import store from '@/store/index'         就:store.state.vote.beforeVoteParams   可以取值;

1)入口文件中要引入同级目录下的:import store from './store'      //import store from './store'/index.js   index.js是省略的写法

vue用的版本是:"vue": "^2.3.3",

vuex用的版本是:"vuex": "^2.3.1",

    并且要加入进来:

  new Vue({
    router,
    store,
    axios,
    template: '<App/>',
    components: { App }
  }).$mount('#app');

2)目录如下:

  

3)在index.js中:

import Vue from 'vue';
import Vuex from 'vuex';
import getters from './getters';
import user from './modules/user';
import permission from './modules/permission';
import vote from './modules/vote';

Vue.use(Vuex);

const store = new Vuex.Store({
    modules: {
        user,
        permission,
        vote
    },
    getters
});

export default store

4)在getter.js中:

我们可以在store中定义getters,第一个参数是state;

传参:定义的Getters会暴露为store.getters对象,也可以接受其他的getters作为第二个参数;

const getters = {
    paramsself:state =>state.vote.beforeVoteParams,
};
export default getters

页面上可以这么用:<p>{{'paramsself:'+$store.getters.paramsself}}</p>

5)在vote.js中:

const vote = {
  state: {
    beforeVoteParams : '',
    index:"queryHoldVolume11115"
  },
  mutations: {
    GET_BEFOREVOTE_PARAMS:(state,item)=>{
      state.beforeVoteParams = item;
    }
  },
  actions: {
    get_beforeVote_params:({commit},item)=>{
      commit('GET_BEFOREVOTE_PARAMS',item)
    },
  }
};

export default vote;

差不多就是这么用的。

state,      <!--状态-->
    
getters,    <!-- 状态的计算属性 -->
    
mutations,  <!-- 用于改变状态 -->
    
actions,   <!-- 可包含异步操作的mutation -->

3.mapGetters

mapGetters辅助函数仅仅是将store中的getters映射到局部计算属性中,用法和mapState类似

原文地址:https://www.cnblogs.com/wpcnblog/p/10973295.html