vuex相关文档
1. 简介
vuex是专为vue.js提供的状态管理模式。使用是非常简单的,记录一下具体使用步骤。
它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
说得通俗点就是,在vue组件中,多个组件要用到同一个数据源,并且通过这个数据源渲染视图,并且数据源发生变化了,组件都要响应式变化。而维护这个数据的方案就是vuex.
2. 安装
<!--npm-->
npm install vuex --save
<!--CDN方式-->
<script src="https://unpkg.com/vuex"></script>
<!--yarn方式-->
yarn add vuex
<!--如果是在模块化的打包系统的话,必须显式安装vuex-->
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
3. 核心
state:驱动应用的数据源;
view:以声明方式将 state 映射到视图;
action: 响应在 view 上的用户输入导致的状态变化;异步操作。在组件中使用是$store.dispath(‘’)
strict: true, 开启严格模式确保state 中的数据只能 mutations 修改
mutations: 使用commit调用页面刷新丢失:修改状态,并且是同步的。在组件中使用$store.commit(‘’,params)。这个和我们组件中的自定义事件类似。
modules: store的子模块,为了开发大型项目,方便状态管理而使用的。
getters: 计算属性(类似于computed):对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
4. state
state就是存储数据源的容器,可以简单这里理解,好比在vue组件中的那个data一样,只不过这是在vuex存储数据的容器。
- 首先用new Vuex.Store()创建vuex实例
const store = new Vuex.Store({ state:{ count : 0 } })
- 如果在模块化打包系统(vue-cli)中是,新建一个store.js
import vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new Vue.Store({ state:{ // 存储数据的容器 count : 0 } }) export default store
- 数据已经有了,怎么在具体组件上面显示数据。一般来说,我们是将store挂在根组件上。这样所有的组件都能拿到store的数据。
假设是在模块化打包系统中(vue-cli),在main.jsimport Vue from 'vue' import App from './App' import vuex from 'vuex' import store from '@/store/store' Vue.use(vuex) new Vue({ el: '#app', store, components: { App }, template: '<App/>' })
- 此时store已经挂在vue的根组件上面了,所以我们在根组件上面输出根组件就可以看到store
在App.vue中<template> <div id="app"> </div> </template><script> export default { name: 'App', data(){ }, created(){ // 输出根组件 console.log(this) } } </script>
- 可以看到根组件的store就是我们之前定义的store,这里我们先只关注state,而this.store.state.count就是我们在store.js定义在state的count。
- 我们在组件上访问count就是this.$store.count,不过要注意的是要想实时响应count的值的话,就要写在计算属性上面
<template> <div id="app"> {{count}} </div> </template><script> export default { name: 'App', computed:{ count(){ return this.$store.state.count } } } </script>
5. getter
有时候我们需要从 store 中的 state 中派生出一些状态,比如我不直接读取state里面值,我想对这里面的值进行一些操作在返回就可以用到getter
- 我需要对list进行一些操作在输出值,不是直接拿到list的值,就可以用到getter了Getter 接受 state 作为其第一个参数:
import vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new Vue.Store({ state:{ // 存储数据的容器 count : 0, list:[ {id:0,name :'zhangsan',status:true}, {id:1,name :'lisi'status:false}, ... ] }, getters:{ getLists(state) { return state.list.filter(item => item.status) } } }) export default store
- 怎么在组件中访问getter? 通过属性访问
Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值store.getters.doneTodos // [{ id: 1, name: 'zhangsan', status: true },...]
- 在上面例子就是
<template> <div id="app"> {{count}} </div> </template><script> export default { name: 'App', computed:{ count(){ return this.$store.state.count }, getList(){ return this.$store.getters.getLists } } } </script>
- 通过方法访问: 可以通过让 getter 返回一个函数,来实现给 getter 传参。这种方式对列表筛选的需求特别有用
export default { name: 'App', data(){ }, getters: { getListById: (function (state) { return function (id) { return state.list.find(function (item) { return item.id === id; }); }; }); } }
- 上面例子中
this.$store.getters.getListById(0) // [{id:0,name :'zhangsan',status:true}]
注意:
getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。其他更多getter东西请参考官网文档,这里不深究~
5. mutation
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
- 接上面的store.js,我们在vuex的实例store里面新增个mutation对象,这个对象存储这我们想要对state对象里数据源的各种操作,而这些具体的操作的函数就叫 commit
import vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new Vue.Store({ state:{ // 存储数据的容器 count : 0 }, mutations:{ increase(state,n){ state.count += n } } }) export default store
- 在mutation里面定义的commit函数,函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。也可以传入额外参数。
例子中的n就是额外参数。
那我们在具体组件中,怎么出发这个mutation里面的修改状态的函数。
我们回到app.vue,比如我们像实现一个小需求,在input输入框中输入数字,然后把这个数字和count相加。<template> <div id="app"> <div>{{counter}}</div> <input type="text" v-model="number"> <button @click="increment">相加</button> </div> </template><script> export default { name: 'App', data(){ number:'' }, methods:{ increment(){ this.$store.commit('increment',parseInt(this.number)) } } } </script>
- 首先我们要知道,在vuex中不能直接的改变state的状态,要通过显式的提交一个commit去出发mutation里面的改变状态的函数。
在组件中,我们用store.commit(‘increment’)去出发mutation的函数,而上面使用this.$store.commit(‘定义在mutation的函数名’,’额外参数’)触发。
当然我们传递的额外参数应该也可以是个对象更加贴近具体需求相应的触发写法mutations:{ increase(state,payload){ state.count += payload.n } }
还可以用另一种直接包含type属性的对象提交mutationthis.$store.commit('increment', { n: 10 })
this.$store.commit({ type: 'increment', amount: 10 })
6. action
现在又多了个action的概念了,Action和mutation类似,按照官网说的:不同之处就是
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
import vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new Vue.Store({ state:{ // 存储数据的容器 count : 0 }, mutations:{ increase(state,n){ state.count += n } }, actions:{ increase (context) { context.commit('increase') } } }) export default store
- Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
这里为什么说context对象是与store实例具有相同方法和属性的对象,先不深究,后面会讲到。- 触发action
Action 通过 store.dispatch 方法触发store.dispatch('increase')
- 写在上面代码就是
this.$store.dispatch('increase')
- 其实很多人应该会在想,既然又了mutation了,那action不就多此一举了吗,关键还真不是,因为mutation是必须同步执行的,不能保护又异步的代码,而action不受限制,我们可以在action里面执行异步操作
参考官网的例子actions: { incrementAsync (context) { setTimeout(() => { context.commit('increment') }, 1000) } }
- 和mutation一样,同样支持荷载形式触发对象方式触发
store.dispatch('incrementAsync', { amount: 10 }) store.dispatch({ type: 'incrementAsync', amount: 10 })
7. module
module的出现是为了解决,当应用变得非常复杂时候,store对象会变得异常臃肿,与是vuex运行我们对store对象分模块管理。
每个模块都有自己的state、mutation、action、getter和嵌套的module。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 的状态