Vue.js-cli配置Vuex

 

Vuex 是什么?

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

什么情况下我应该使用 Vuex?

虽然 Vuex 可以帮助我们管理共享状态,但也附带了更多的概念和框架。这需要对短期和长期效益进行权衡。

如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 global event bus 就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。引用 Redux 的作者 Dan Abramov 的话说就是:

Flux 架构就像眼镜:您自会知道什么时候需要它。

 

配置Vuex:

  1、安装vuex

    cnpm install vuex --save

  2、在项目中新建vuex模块”文件夹,并新建store.js文件。

  import Vue from "vue"
  import Vuex from "vuex"
  Vue.use(Vuex);
  export const store = new Vuex.Store({
      state:{
          text:'测试文字',
      },
  });

  3、min.js文件中引入vuex文件 ,并在新建Vue 实例的时候添加store。

  import { store } from './vuex/store'
  new Vue({
      store: store,
      el: '#app',
      router,
      template: '<App/>',
      components: { App }
  })

使用Vuex:

  1、Vuex 使用computed获取store数据:

  a、由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在“计算属性”中返回某个状态。

  组件:

<template>
  <div class="mainbody" style="">
    <div>
      **{{text}}**
    </div>
  </div>
</template>
<script>
  export default {
    computed:{
      text(){
        return this.$store.state.text;
      }
    }
  }
</script>
<style scoped>
  .mainbody div{margin-top: 200px;}
</style>

  b、mapState 辅助函数。当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。

  组件:      

<template>
  <div class="mainbody" style="">
    <div>
      <p> **{{text}}**</p> 
      <p>{{customTypeArr}}</p>
    </div>
  </div>
</template>
<script>
  import { mapState } from 'vuex'
  export default {
    components: {
    },
    computed:{
      ...mapState({
        text : state => state.text,
        customTypeArr : state => state.customTypeArr
      }),
    },
  }
</script>
<style scoped>
  .mainbody div{margin-top: 200px;}
</style>

  2、Getters

  a、有时候我们需要从 store 中的 state 中派生出一些状态,这样我们就需要对state 中的属性值进行操作。Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);
export const store = new Vuex.Store({
    state:{
        text:'Vuex测试文字',
    },
    getters:{
        changeText(state){
            var text = state.text+"11111111111111";
            return text
        }
    }
});

   b、mapGetters 辅助函数,仅仅是将 store 中的 getter 映射到局部计算属性。如果你想将一个 getter 属性另取一个名字,使用对象形式。

  组件:

<template>
  <div class="mainbody" style="">
    <div>
      <p> **{{text}}**</p> 
      <p>{{changeText}}</p>
      <!-- <p> {{text2}}</p>  -->
    </div>
  </div>
</template>
<script>
  import { mapState } from 'vuex'
  import { mapGetters } from 'vuex'
  export default {
    computed:{
      ...mapGetters([
        'changeText'
      ]),
      // ...mapGetters({
      //   'text2' : 'changeText'
      // }),
      ...mapState({
        text : state => state.text
      })
    },
  }
</script>
<style scoped>
  .mainbody div{margin-top: 200px;}
</style>

  3、Mutations

  Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

  store.js

    state:{
        text:'Vuex测试文字',
        count : 0
    }, 
    mutations :{
        increment (state,payload) {
            state.count+=payload
        }
    }

  组件:

<template>
  <div class="mainbody" style="">
    <div>
      <p> **{{text}}**</p> 
      <p>{{changeText}}</p>
      <p>{{count}}</p>
    </div>
    <button @click="countAdd(2)">增加</button>
  </div>
</template>
<script>
  import { mapState } from 'vuex'
  import { mapGetters } from 'vuex'
  export default {
    computed:{
      ...mapState({
        text : state => state.text,
      }),
      ...mapGetters([
        'changeText',
        'count'
      ]),
    },
    methods:{
      countAdd(n){
        this.$store.commit('increment',n)
      }
    } 
  }
</script>
<style scoped>
  .mainbody div{margin-top: 200px;}
</style>

  4、Actions

  Action 类似于 mutation,不同在于:

  Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。

  Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

  

    getCountAdd(){      //Action 通过 store.dispatch 方法触发:
        this.$store.dispatch("getSelectEmployeeList");  
      }

  store.js

    mutations :{
        increment (state,payload) {
            state.count+=payload;
        },
        getSelectEmployeeList(state,payload){
            state.count = payload;
        },
    },
    actions:{
        getSelectEmployeeList(context) {                  //获取人员信息
            let Arr = [];
            axios.post(Sale.html_url + Sale.Apilist.selectEmployeeList, {}).then(function (data) {
                var Arr  = data.data.data;
                context.commit('getSelectEmployeeList', Arr[0].id);
            }).catch(function (e) { });
        },
    }

  mapActions 辅助函数

  import { mapState } from 'vuex'
  import { mapGetters } from 'vuex'
  import { mapActions } from 'vuex'
  export default {
    computed:{
      ...mapState({
        text : state => state.text,
      }),
      ...mapGetters([
        'changeText',
        'count'
      ]),
    },
    methods:{
      // getCountAdd(){      //Action 通过 store.dispatch 方法触发:
      //   this.$store.dispatch("getSelectEmployeeList");  
      // }
      ...mapActions([
        "getSelectEmployeeList"
      ]),
    } 
  }

  组合 Action

 

  5、Moudle

   由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

store.js

import Vue from "vue"
import Vuex from "vuex"
import {moduleA }from './a'
Vue.use(Vuex);
export const store = new Vuex.Store({
  modules: {
    a: moduleA,
  }
})

a.js

import Vue from "vue"
import axios from 'axios';
import {apilist} from '../api/apiList'
var Sale = Vue.prototype;
export const moduleA = {
  state:{
        text:'Vuex测试文字',
        count : 0
    },
    getters:{
        changeText : state =>{
            var text = state.text+"getters";
            return text
        },
        count: state =>{
            var text = state.count;
            return text
        },
    },
    mutations :{
        increment (state,payload) {
            state.count += payload;
        },
        getSelectEmployeeList(state,payload){
            state.count = payload;
        },
    },
    actions:{
        getSelectEmployeeList(context) {                  //获取人员信息
            let Arr = [];
            axios.post(Sale.html_url + Sale.Apilist.selectEmployeeList, {}).then(function (data) {
                var Arr  = data.data.data;
                context.commit('getSelectEmployeeList', Arr[0].id);
            }).catch(function (e) { });
        }
    }
}

 

 

 

参考:https://www.cnblogs.com/moxiaowohuwei/p/7999034.html

官网:https://vuex.vuejs.org/zh-cn/intro.html

posted @ 2018-05-02 16:33  $坐看云起$  阅读(171)  评论(0编辑  收藏  举报