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

在 Vue 之后引入 vuex 会进行自动安装:

<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>

可以通过 https://unpkg.com/vuex@2.0.0 这样的方式指定特定的版本。

NPM

npm install vuex --save

State

在 Vue 组件中获得 Vuex 状态

const Counter = {template: `<div>{{ count }}</div>`,
  computed: {count () {return this.$store.state.count}}
}

mapState 辅助函数

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

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'export default {// ...
  computed: mapState({// 箭头函数可使代码更简练count: state => state.count,// 传字符串参数 'count' 等同于 `state => state.count`countAlias: 'count',// 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {return state.count + this.localCount}})
}

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: mapState([// 映射 this.count 为 store.state.count'count'
])

对象展开运算符

mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。

computed: {localComputed () { /* ... */ },// 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({// ...
  })
}

Getter

有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:

computed: {doneTodosCount () {return this.$store.state.todos.filter(todo => todo.done).length}
}

如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它——无论哪种方式都不是很理想。

Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

Getter 接受 state 作为其第一个参数:

const store = new Vuex.Store({state: {todos: [{ id: 1, text: '...', done: true },{ id: 2, text: '...', done: false }]},getters: {doneTodos: state => {return state.todos.filter(todo => todo.done)}}
})

Getter 会暴露为 store.getters 对象:

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

Getter 也可以接受其他 getter 作为第二个参数:

getters: {// ...doneTodosCount: (state, getters) => {return getters.doneTodos.length}
}store.getters.doneTodosCount // -> 1

我们可以很容易地在任何组件中使用它:

computed: {doneTodosCount () {return this.$store.getters.doneTodosCount}
}

你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

getters: {// ...getTodoById: (state) => (id) => {return state.todos.find(todo => todo.id === id)}
}store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

mapGetters 辅助函数

mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

import { mapGetters } from 'vuex'export default {// ...
  computed: {// 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters(['doneTodosCount','anotherGetter',// ...
    ])}
}

如果你想将一个 getter 属性另取一个名字,使用对象形式:

mapGetters({// 映射 `this.doneCount` 为 `store.getters.doneTodosCount`doneCount: 'doneTodosCount'
})

Mutation

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

const store = new Vuex.Store({state: {count: 1},mutations: {increment (state) {// 变更状态state.count++}}
})

store.commit('increment')

当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变:

mutations: {increment (state, payload) {state.count += payload.amount}
}

使用常量替代 Mutation 事件类型

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'const store = new Vuex.Store({state: { ... },mutations: {// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {// mutate state
    }}
})

在组件中提交 Mutation

你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

import { mapMutations } from 'vuex'export default {// ...
  methods: {...mapMutations(['increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`// `mapMutations` 也支持载荷:'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),...mapMutations({add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })}
}

Action

Action 类似于 mutation,不同在于:

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

让我们来注册一个简单的 action:

const store = new Vuex.Store({state: {count: 0},mutations: {increment (state) {state.count++}},actions: {increment (context) {context.commit('increment')}}
})

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

实践中,我们会经常用到 ES2015 的 参数解构 来简化代码(特别是我们需要调用 commit 很多次的时候):

actions: {increment ({ commit }) {commit('increment')}
}

分发 Action

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:

actions: {incrementAsync ({ commit }) {setTimeout(() => {commit('increment')}, 1000)}
}

Actions 支持同样的载荷方式和对象方式进行分发:

// 以载荷形式分发
store.dispatch('incrementAsync', {amount: 10
})// 以对象形式分发
store.dispatch({type: 'incrementAsync',amount: 10
})

来看一个更加实际的购物车示例,涉及到调用异步 API分发多重 mutation

actions: {checkout ({ commit, state }, products) {// 把当前购物车的物品备份起来const savedCartItems = [...state.cart.added]// 发出结账请求,然后乐观地清空购物车
    commit(types.CHECKOUT_REQUEST)// 购物 API 接受一个成功回调和一个失败回调
    shop.buyProducts(products,// 成功操作() => commit(types.CHECKOUT_SUCCESS),// 失败操作() => commit(types.CHECKOUT_FAILURE, savedCartItems))}
}

在组件中分发 Action

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

import { mapActions } from 'vuex'export default {// ...
  methods: {...mapActions(['increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`// `mapActions` 也支持载荷:'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),...mapActions({add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })}
}

Module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {state: { ... },mutations: { ... },actions: { ... },getters: { ... }
}const moduleB = {state: { ... },mutations: { ... },actions: { ... }
}const store = new Vuex.Store({modules: {a: moduleA,b: moduleB}
})store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

一般项目结构

Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:

  1. 应用层级的状态应该集中到单个 store 对象中。

  2. 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。

  3. 异步逻辑都应该封装到 action 里面。

只要你遵守以上规则,如何组织代码随你便。如果你的 store 文件太大,只需将 action、mutation 和 getter 分割到单独的文件。

对于大型应用,我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例:

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store├── index.js          # 我们组装模块并导出 store 的地方├── actions.js        # 根级别的 action├── mutations.js      # 根级别的 mutation└── modules├── cart.js       # 购物车模块└── products.js   # 产品模块

请参考购物车示例。

总结

安装vuex

npm install --save vuex
<!--这里假定你已经搭好vue的开发环境了--> 

配置vuex

1、首先创建一个js文件,假定这里取名为store.js
2、在main.js文件中引入上面创建的store.js

//main.js内部对store.js的配置
import store from '"@/store/store.js'
//具体地址具体路径
new Vue({el: '#app',store, //将store暴露出来template: '<App></App>',components: { App }
});

store.js中的配置

import Vue from 'vue'; //首先引入vue
import Vuex from 'vuex'; //引入vuex
Vue.use(Vuex) export default new Vuex.Store({state: { // state 类似 data//这里面写入数据
    },getters:{ // getters 类似 computed // 在这里面写个方法
    },mutations:{ // mutations 类似methods// 写方法对数据做出更改(同步操作)
    },actions:{// actions 类似methods// 写方法对数据做出更改(异步操作)
    }
})

使用vuex

我们约定store中的数据是以下形式

state:{goods: {totalPrice: 0,totalNum:0,goodsData: [{id: '1',title: '好吃的苹果',price: 8.00,image: 'https://www.shangdian.com/static/pingguo.jpg',num: 0},{id: '2',title: '美味的香蕉',price: 5.00,image: 'https://www.shangdian.com/static/xiangjiao.jpg',num: 0}]}
},
gettles:{ //其实这里写上这个主要是为了让大家明白他是怎么用的,
    totalNum(state){let aTotalNum = 0;state.goods.goodsData.forEach((value,index) => {aTotalNum += value.num;})return aTotalNum;},totalPrice(state){let aTotalPrice = 0;state.goods.goodsData.forEach( (value,index) => {aTotalPrice += value.num * value.price})return aTotalPrice.toFixed(2);}
},
mutations:{reselt(state,msg){console.log(msg) //我执行了一次;state.goods.totalPrice = this.getters.totalPrice;state.goods.totalNum = this.getters.totalNum;},reduceGoods(state,index){ //第一个参数为默认参数,即上面的state,后面的参数为页面操作传过来的参数state.goodsData[index].num-=1;let msg = '我执行了一次'this.commit('reselt',msg);},addGoods(state,index){state.goodsData[index].num+=1;let msg = '我执行了一次'this.commit('reselt',msg);/**想要重新渲染store中的方法,一律使用commit 方法 你可以这样写 commit('reselt',{state: state})也可以这样写 commit({type: 'reselt',state: state })主要看你自己的风格**/}
},
actions:{//这里主要是操作异步操作的,使用起来几乎和mutations方法一模一样//除了一个是同步操作,一个是异步操作,这里就不多介绍了,//有兴趣的可以自己去试一试//比如你可以用setTimeout去尝试一下
}

好了,简单的数据我们就这样配置了,接下来看看购物车页面吧;

第一种方式使用store.js中的数据(直接使用)

<template><div id="goods" class="goods-box"><ul class="goods-body"><li v-for="(list,index) in goods.goodsData" :key="list.id"><div class="goods-main"><img :src="list.image"></div><div class="goods-info"><h3 class="goods-title">{{ list.title }}</h3><p class="goods-price">¥ {{ list.price }}</p><div class="goods-compute"><!--在dom中使用方法为:$store.commit()加上store.js中的属性的名称,示例如下--><span class="goods-reduce" @click="$store.commit('reduceGoods',index)">-</span><input readonly v-model="list.num" /><span class="goods-add" @click="$store.commit('addGoods',index)">+</span></div></div></li></ul><div class="goods-footer"><div class="goods-total">合计:¥ {{ goods.totalPrice }}<!--如果你想要直接使用一些数据,但是在computed中没有给出来怎么办?可以写成这样{{ $store.state.goods.totalPrice }}或者直接获取gettles里面的数据{{ $store.gettles.totalPrice }}--></div><button class="goods-check" :class="{activeChecke: goods.totalNum <= 0}">去结账({{ goods.totalNum }})</button></div></div>
</template>
<script>export default {name: 'Goods',computed:{goods(){return this.$store.state.goods;}}}
</script>

如果上面的方式写参数让你看的很别扭,我们继续看第二种方式

第一种方式使用store.js中的数据(通过辅助函数使用)

<!--goods.vue 购物车页面-->
<template><div id="goods" class="goods-box"><ul class="goods-body"><li v-for="(list,index) in goods.goodsData" :key="list.id"><div class="goods-main"><img :src="list.image"></div><div class="goods-info"><h3 class="goods-title">{{ list.title }}</h3><p class="goods-price">¥ {{ list.price }}</p><div class="goods-compute"><span class="goods-reduce" @click="goodsReduce(index)">-</span><input readonly v-model="list.num" /><span class="goods-add" @click="goodsAdd(index)">+</span></div></div></li></ul><div class="goods-footer"><div class="goods-total">合计:¥ {{ goods.totalPrice }}<!--gettles里面的数据可以直接这样写{{ totalPrice }}--></div><button class="goods-check" :class="{activeChecke: goods.totalNum <= 0}">去结账({{ goods.totalNum }})</button></div></div>
</template>
<script>import {mapState,mapGetters,mapMutations} from 'vuex';/**上面大括弧里面的三个参数,便是一一对应着store.js中的state,gettles,mutations这三个参数必须规定这样写,写成其他的单词无效,切记毕竟是这三个属性的的辅助函数**/export default {name: 'Goods',computed:{...mapState(['goods']) ...mapGetters(['totalPrice','totalNum'])/**‘...’ 为ES6中的扩展运算符,不清楚的可以百度查一下如果使用的名称和store.js中的一样,直接写成上面数组的形式就行,如果你想改变一下名字,写法如下...mapState({goodsData: state => stata.goods})**/},methods:{...mapMutations(['goodsReduce','goodsAdd']),/**这里你可以直接理解为如下形式,相当于直接调用了store.js中的方法goodsReduce(index){// 这样是不是觉得很熟悉了?},goodsAdd(index){}好,还是不熟悉,我们换下面这种写法onReduce(index){ //我们在methods中定义了onReduce方法,相应的Dom中的click事件名要改成onReducethis.goodsReduce(index)//这相当于调用了store.js的方法,这样是不是觉得满意了}**/}}
</script>

Module

const moduleA = {state: { /*data**/ },mutations: { /**方法**/ },actions: { /**方法**/ },getters: { /**方法**/ }
}const moduleB = {state: { /*data**/ },mutations: { /**方法**/ },actions: { /**方法**/ }
}export default new Vuex.Store({modules: {a: moduleA,b: moduleB}
})//那怎么调用呢?看下面!//在模块内部使用
state.goods //这种使用方式和单个使用方式样,直接使用就行//在组件中使用
store.state.a.goods //先找到模块的名字,再去调用属性
store.state.b.goods //先找到模块的名字,再去调用属性

参考地址:《震惊!喝个茶的时间就学会了vuex》

vue从入门到进阶:Vuex状态管理(十)相关推荐

  1. flux react php,Vue的Flux框架之Vuex状态管理器

    学习vue之前,最重要是弄懂两个概念,一是"what",要理解vuex是什么:二是"why",要清楚为什么要用vuex. Vuex是什么? Vuex 类似 Re ...

  2. Vue 从入门到进阶之路(十四)

    之前的文章我们对 vue 的基础用法已经有了很直观的认识,本章我们来看一下 vue 中的生命周期函数. 上图为 Vue官方为我们提供的完整的生命周期函数的流程图,下面的案例我们只是走了部分情况流程,但 ...

  3. Vue项目 成员管理系统 Vuex状态管理(10)

    Vuex是一个专为Vue.js应用程序开发的状态管理模式.它采用集中式储存管理应用的所有组件的转台并以相应的规则保证装填以一中可预测的方式发生变化. Vuex可以将组件中的某些属性.值或者方法拿出来统 ...

  4. vuex状态管理模式:入门demo(状态管理仓)

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

  5. Vue学习笔记(五)—— 状态管理Vuex

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

  6. Vue组件传值存在的弊端-Vuex状态管理

    以下内容纯属个人理解,旨在记录和分享. 导入 使用Vue组件传值,可以实现父子组件之间的数据交换.但实际上,在应用过程中仍然存在很多不便之处: 当存在多层组件嵌套时,组件之间的传值将会变得极度麻烦和繁 ...

  7. 在vue项目中引用vuex状态管理工具

    在vue项目中引用vuex状态管理工具 一.vuex是什么? 二.使用步骤 1.引入库 2.在main.js文件引入配置 3.配置store/index.js文件 4.获取state数据 5.获取ge ...

  8. vuex状态管理,用最朴实的话讲解最难懂的技术,

    一.案例演示 引入vuex 1.利用npm包管理工具,进行安装 vuex.在控制命令行中输入下边的命令就可以了. npm n install vuex --save 需要注意的是这里一定要加上 –sa ...

  9. Vuex 状态管理的工作原理

    Vuex 状态管理的工作原理 为什么要使用 Vuex 当我们使用 Vue.js 来开发一个单页应用时,经常会遇到一些组件间共享的数据或状态,或是需要通过 props 深层传递的一些数据.在应用规模较小 ...

最新文章

  1. 事件相机特征跟踪-概率数据关联法
  2. Python学习札记(六)
  3. 中国移动互联网2018年度报告:八大关键词总结与十大趋势
  4. python写mysql脚本_使用python写一个监控mysql的脚本,在zabbix web上加上模板
  5. 学点 C 语言(20): 数据类型 - 指针
  6. 关于计算机的英语作文九年级,实用的九年级英语作文合集6篇
  7. C++中的模板展开问题
  8. 用户启动计算机并登录win7,win7电脑设置开机登录界面的方法?
  9. Halcon_3D点云筛选,目标轮廓提取,切平面求取目标间隙宽度
  10. butterworth matlab,Matlab实现Butterworth滤波器
  11. 易优CMS:arcpagelist 瀑布流分页列表
  12. 政务内网、政务外网、政务专网
  13. [Xcelsius]从Xcelsius中导出Excel表格
  14. Ubuntu日常使用命令记录
  15. 微信公众平台开发入门:[8]聊天机器人可开发
  16. SELinux权限问题解决
  17. C语言|博客作业05
  18. PDMS二次开发产品Naki.CI(二):升级到1.0.1版本
  19. ThinkPHP5.0+七牛云SDK文件上传
  20. Elesticsearch基础

热门文章

  1. jq实现文字个数限制_Android实现类似钉钉水印背景功能
  2. Android之一起制作简易唱片播放器
  3. Android判断应用是否拥有某种权限
  4. swift_013(Swift 的运算符)
  5. python关闭浏览器、未过期的session_session.cookie_lifetime = 0时,为什么会话在浏览器关闭时不会过期?...
  6. python 地址模糊匹配_使用python处理selenium中的xpath定位元素的模糊匹配问题
  7. Ubuntu16.04LTS安装集成开发工具IDE: CodeBlocks 和Eclipse-cdt
  8. C++入门经典-例9.4-默认模板参数
  9. Android仿QQ界面
  10. Mac中使用port升级gcc版本