一文让你彻底搞懂Vuex,满满的干货

开发 前端
可以把多个组件都需要的变量全部存储到一个对象里面,然后这个对象放在顶层的 vue 实例中,让其他组件可以使用。这样多个组件就可以共享这个对象中的所有属性。

[[429955]]

官方解释:Vuex 是专为 vue.js 应用程序开发的状态管理模式。

一、Vuex 是做什么呢?

什么是状态管理?

简单地讲:可以把多个组件都需要的变量全部存储到一个对象里面,然后这个对象放在顶层的 vue 实例中,让其他组件可以使用。这样多个组件就可以共享这个对象中的所有属性。

有些同学想着,这么简单我们自己在vue顶层定义一个对象不就可以实现共享了?我们发现虽然数据可以获取到,但是如果在某个组件内,数据改变了,那我们如何修改数据,让此数据在其他组件内保持最新呢?

我们的vuex就是为了提供一个在多个组件间共享状态的插件,而且能够实现实时响应。

二、Vuex 使用

vuex 是管理组件之间通信的一个插件,所以使用之前必须安装。

2.1、安装

1)使用 script 方式引入

  1. <script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script> 

2)使用包管理

  1. npm install vuex --save //yarn add vuex 

注意:vuex 必须依赖 vue 使用

2.2、搭建 store 实例

创建一个 store 文件夹,新建 index.js

  1. import Vue from "vue"
  2. import Vuex from "vuex"
  3.  
  4. Vue.use(Vuex);//使用vuex 
  5.  
  6. export default new Vuex.Store({ 
  7.     state:{}, 
  8.   mutations:{}, 
  9.   getters:{}, 
  10.   actions:{}, 
  11.   modules:{} 
  12. }) 

 在 main.js 处,挂载 store

  1. import store from './store' 
  2.  
  3. new Vue({ 
  4.  router, 
  5.  render: h=>h(App) 
  6. }) 
  7.  
  8. //相当于 
  9. // Vue.prototype.$store = store 

 2.3、使用状态

  1. // store 中定义状态 
  2. state:{ 
  3.     statue: '在线' 
  4.  
  5. //在组件内使用 
  6. <div>组件内数据:{{ $store.state.status }} </div> 
  7. //在 js 中使用 
  8. mounted(){ 
  9.     console.log( this.$store.state.status ) 

三、Vuex 的五大核心

3.1、state

state 存放 vuex 的基本数据,用来存储变量的。

单一状态树

Vuex 使用单一状态树,即用一个对象就包含了全部的状态数据。state 作为构造器选项,定义了所有我们需要的基本状态参数。

在组件中引用 state 数据方式:

1)通过 vue 的 computed 获取 vuex 的 state

  1. export default new Vuex.Store({ 
  2.  state:{ 
  3.   online:true 
  4.  } 
  5. }) 
  6.  
  7.  
  8. computed:{ 
  9.  status(){ 
  10.   return this.$store.state.online 
  11.  } 

store 中的数据发生改变时,都会重新求取计算属性,并更新相关 DOM。

2)如果需要使用多个参数时,都使用 computed 计算属性,就会使代码变的有些冗余和复杂,此时我们就可以借助 mapState 辅助函数。

  1. //state 中数据比较多,引用到一个组件内 
  2. export default new Vuex.Store({ 
  3.  state:{ 
  4.   online:true
  5.    per:[ 
  6.     {name:'qq',age:18} 
  7.    ], 
  8.   role:'管理员' 
  9.  } 
  10. }) 
  11.  
  12. //组件内 
  13. import { mapState } from 'vuex' 
  14.  
  15. export default { 
  16.   name'App'
  17.   computed: mapState({ 
  18.    online: state => state.online, 
  19.     per: 'per', // 'per'就相当于 state.per 
  20.     role: 'role' // 'role'就相当于 state.role 
  21.   }) 

vuex 使用单一状态树来管理应用层级的全部状态,单一状态树能够让我们最直接的方式找到某个状态的片段,而且之后的维护和调试过程,也可以非常方便管理和维护。

3.2、getters

从 store 中获取一些 state 变异后的状态。

使用的时候一般有两种方式:

1)返回的结果只依赖于 state 中的数据

  1. export default new Vuex.Store({ 
  2.  state:{ 
  3.   count:2, 
  4.  }, 
  5.  getters:{ 
  6.    //返回 count 的 2 倍数据 
  7.   countDouble(state){ 
  8.    return state.count*2 
  9.   } 
  10.  } 
  11. }) 
  12.  
  13. //组件中引用 
  14. <div> 获取countDouble:{{ $store.getters.countDouble }} </div> 
  15. //运行结果 
  16. 获取countDouble:4 

此处,$store.getters.countDouble 的使用与上边的 $store.state.count 是一样的。

2)getters 中返回的变异结果,依赖于某个 getters 中属性返回结果

  1. export default new Vuex.Store({ 
  2.  state:{ 
  3.   count:2, 
  4.  }, 
  5.  getters:{ 
  6.    //返回 count 的 2 倍数据 
  7.   countDouble( state ){ 
  8.    return state.count * 2 
  9.   } 
  10.    //返回 countDouble 的 2 倍数据 
  11.    countDoubleT( state , getters ){ 
  12.     return getters.countDouble * 2 
  13.    } 
  14.  } 
  15. }) 
  16.  
  17. //组件中引用 
  18. <div> 获取countDouble:{{ $store.getters.countDoubleT }} </div> 
  19. //运行结果 
  20. 获取countDouble:8 

3.3、mutations

vuex 的store 状态的更新唯一方式:提交 Mutation。

Mutations 主要包括两部分:

字符串的事件类型

一个回调函数,该回调函数的第一个参数就是 state。

1)mutation 中的方法通过 commit 调用,不传参数使用:

  1. export default new Vuex.Store({ 
  2.  state:{ 
  3.   count:2, 
  4.  }, 
  5.  mutations:{ 
  6.   incrs(state){ 
  7.    // count 加 1  
  8.    state.count++ 
  9.   } 
  10.  } 
  11. }) 
  12.  
  13. //组件调用 
  14.  
  15. <button @click=" $store.commit('incrs') " >+</button> 
  16. {{$store.state.count}} 

按钮每点一次,count 就会自加一次。

2)mutations 传递参数

我们点击加按钮时,指定每次点击增加的数值,如下:

  1. export default new Vuex.Store({ 
  2.  state:{ 
  3.   count:2, 
  4.  }, 
  5.  mutations:{ 
  6.   addNum( state,n ){ 
  7.    // count 加 1  
  8.    state.count +=n 
  9.   } 
  10.  } 
  11. }) 
  12.  
  13. //组件调用 
  14.  
  15. <button @click=" $store.addNum( 'incrs' , 5 ) " >+</button> 
  16. {{$store.state.count}} 
  17.  
  18. //运行结果 
  19. 每点一次按钮,count 增加 5 

上个实例传递的是一个参数,如果我们需要传递多个参数时,该如何实现呢?

3)mutations 传递多个参数

  1. export default new Vuex.Store({ 
  2.  state:{ 
  3.   count:2, 
  4.  }, 
  5.  mutations:{ 
  6.   addNum(state,payload){ 
  7.     // payload 是传递过来的参数对象 
  8.     state.count += payload.count 
  9.   } 
  10.  } 
  11. }) 
  12.  
  13. //组件调用 
  14.  
  15. <button @click="addTen" >加10</button> 
  16. {{$store.state.count}} 
  17. export default
  18. methods:{ 
  19.  addTen(){ 
  20.   this.$store.commit({ 
  21.     type:'addNum'
  22.      count:10, 
  23.         ...//可以传任意多个参数 
  24.     }) 
  25.   } 
  26.  } 
  27. //运行结果 
  28. 每点一次按钮,count 增加 10 

上述方法是 mutations 特殊的提交封装。包含了 type 属性的对象,将整个 commit 的对象作为 payload 使用。

3.4、actions

mutations 提交更新数据的方法,必须是同步的,如果是异步使用就会出现问题,然后在项目开发中往往就会用到异步更新,比如网路请求数据。

actions 是类似于 mutation,功能大致相同,但是 actions 是用来替代 mutations 进行异步操作的。

1)actions 的基本使用

  1. actions:{ 
  2.  aUpdateCount(context){ 
  3.   setTimeout(()=>{ //使用定时器模拟异步操作 
  4.    context.commit('updateCount'
  5.   },2000) 
  6.  } 
  7. }, 
  8. mutations:{ 
  9.  updateCount(state){ 
  10.   state.count = 5201314 
  11.  }, 
  12.  
  13. // 组件内使用 
  14. {{$store.state.count}} 
  15. <button @click="$store.dispatch('aUpdateCount')">异步更新count</button> 
  16.  
  17. //运行结果 
  18. 点击按钮,两秒后更新 count 值为5201314 

值得注意的是,使用 actions 异步更新数据的时候,还是需要经过 mutations 中的方法,state 中的数据只能由 mutations 中的方法修改。

调用 mutations 中的方法,使用 commit 调用。

调用 actions 中的方法,使用 dispatch 调用。

2)异步更新的时候,也可以带参数

  1. // 功能:点击按钮,指定 count 修改的值 
  2. actions:{ 
  3.  aUpdateCount( context, payload ){ 
  4.   setTimeout(()=>{ //使用定时器模拟异步操作 
  5.    context.commit'updateCount' , payload ) 
  6.   },2000) 
  7.  } 
  8. }, 
  9. mutations:{ 
  10.  updateCount( state , payload ){ 
  11.   state.count = payload 
  12.  }, 
  13.  
  14. // 组件内使用 
  15. {{$store.state.count}} 
  16. <button @click="$store.dispatch( 'aUpdateCount', '我爱前端' )">异步更新count</button> 
  17.  
  18. //运行结果 
  19. 点击按钮,两秒后更新 count 值为: 我爱前端 

3)传入异步参数

  1. actions:{ 
  2.  //传入promise 
  3.  updateData(context,payload){ 
  4.   return new Promise((resolve,reject)=>{ 
  5.    setTimeout(()=>{ 
  6.     resolve('我学会了'
  7.    },2000) 
  8.   }) 
  9.  }, 
  10.  
  11. //组件内调用 
  12. <button @click="ok">promise执行成功,返回"我学会了"</button> 
  13. methods:{ 
  14.  ok(){ 
  15.   this.$store.dispatch('updateData').then((res)=>{ 
  16.    console.log(res) 
  17.   }) 
  18.  }, 
  19.  
  20. //运行结果 
  21. 点击按钮,两秒后打印:我学会了 

 3.5、modules

modules 是模块的意思,vue 使用单一状态树,项目越来越大,store 中的数据越来越多,不便于数据的管理和维护,代码也会变得臃肿。因此使用 modules ,把数据划分到对应的某个模块,既便于开发,也提高代码的可读性。

1)modules 简单使用

  1. import Vue from 'vue' 
  2. import Vuex from 'vuex' 
  3. import { Increase } from './mutation_type.js' 
  4. Vue.use(Vuex) 
  5. export default new Vuex.Store({ 
  6.   state: {}, 
  7.   actions: {}, 
  8.   getters: { }, 
  9.   mutations: { }, 
  10.   modules:{ 
  11.     a:{ 
  12.       state:{}, 
  13.       getters:{}, 
  14.       mutations:{}, 
  15.       actions:{} 
  16.     }, 
  17.     b:{ 
  18.       state:{}, 
  19.       getters:{}, 
  20.       mutations:{}, 
  21.       actions:{} 
  22.     } 
  23.   }, 
  24. }) 
  25.  
  26. //也可以整理为 
  27. const moduleA = { 
  28.   state:{}, 
  29.   getters:{}, 
  30.   mutations:{}, 
  31.   actions:{} 
  32. const moduleB = { 
  33.   state:{}, 
  34.   getters:{}, 
  35.   mutations:{}, 
  36.   actions:{} 
  37. Vue.use(Vuex) 
  38. export default new Vuex.Store({ 
  39.   state: {}, 
  40.   actions: {}, 
  41.   getters: { }, 
  42.   mutations: { }, 
  43.   modules:{ 
  44.     a: moduleA, 
  45.     b: moduleB 
  46.   }, 
  47. }) 

 2)模块中的数据如何使用呢?

  1. const moduleA = { 
  2.   state:{ 
  3.     aName:'我是模块a的数据' 
  4.   }, 
  5.   getters:{}, 
  6.   mutations:{}, 
  7.   actions:{} 
  8.  
  9. // 组件内引用 
  10. {{ $store.state.a.aName }} 

 3)调用模块内的 mutations 中的方法,如何调用呢?

  1. $store.commit('aChangeName'

调取模块内的 mutations 中的方法,与之前是一模一样的,程序会先从第一层 store 中查找方法,找不到方法时会继续去模块中查找。

4)调用模块内的 getters 内方法

  1. $store.getters.getName 

需要注意的是,getters 中方法都是对 state 中数据变异,如果模块的 getters 方法需要根 store 中的 state 呢?

  1. getName(state,getters , rootState){ 
  2.   // state 表示当前模块的 state 
  3.   // getters表示当前模块的getters 
  4.   //rootState 表示根 store 内的state 

5)模块内的 actions 中的方法,使用 commit 调用 mutations 中方法时,只能调用本模块内的 mutations 方法,不能调用外层的。

四、Vuex 数据响应原理

Vuex 的 store 中的 state 是响应式的,当 state 中数据发生改变时,vue 组件会自动更新。这就要求我们必须遵守一些vuex对应的规则:

提前在 store 中初始化好所需的属性。

说人话,就是必须在state中定义的属性才能做到响应式,如果是后加或删除的,无法做到响应式。

举个栗子:

  1. mutations:{ 
  2.  changeName(state){ 
  3.   state.info.name = '爱学习的前端人' 
  4.  }, 
  5.  addAdrs(state){ 
  6.   state.info['address'] = "陕西西安" 
  7.  }, 
  8.        
  9. {{this.$store.state.info}} 
  10. <button @click="$store.commit('changeName')">修改姓名</button> 
  11. <button @click="$store.commit('addAdrs')">增加地址</button>      

此时点击修改姓名的时候,可以做到响应式,而点击“增加地址”按钮时,页面没有任何反应,但是在开发者模式中可以看到数据有变化。

我们要响应式,该如何实现呢?

  1. addAdrs(state){ 
  2.   
  3.   state.info['address'] = "陕西西安" 
  4.    
  5.   //修改为: 
  6.   Vue.set(state.info,'address','陕西西安')   
  7.    
  8.  }, 

 同样的如果要删除 age 属性时,使用 delete 也做不到响应式,需要修改为 Vue.delete。

实例:响应式删除 age 属性

  1. deleteAge(state){ 
  2.    
  3.  //delete state.info.age 
  4.    
  5.  //修改为   
  6.  Vue.delete(state.info,'age'
  7. }, 
  8.   
  9. //组件内容 
  10. {{this.$store.state.info}} 
  11. <button @click="$store.commit('deleteAge')">删除年龄</button> 

五、类型常量

在 mutation 中定义很多事件类型,也就是方法名。当项目越来越大时,Vuex 管理的状态越来越多,需要更新状态的情况越来越多,那么意为着 Mutations 中的方法名越来越多,方法过多时,使用的时候需要花费大量精力去记住或来回切换文件找方法名,这样很容易出错,所以推荐大家使用一个常量,即使方法名出错了,也会将错就错,程序并不会发生异常。

如:

  1. // 新建 mutation_type.js 文件 
  2. //导出一个常量 
  3. export const Increase = 'increase' 
  4.  
  5. // store.js文件 
  6. import Vue from 'vue' 
  7. import Vuex from 'vuex' 
  8. import { Increase } from './mutation_type.js' 
  9. Vue.use(Vuex) 
  10. export default new Vuex.Store({ 
  11.   state:{ 
  12.     count:2, 
  13.   }, 
  14.   mutations:{ 
  15.     [Increase](state){ 
  16.       state.count++ 
  17.     }, 
  18.   } 
  19. }) 
  20.  
  21. //组件内容 
  22. {{ $store.state.count }} 
  23. <button @click="add">加10</button>  
  24. import { Increase } from './store/mutation_type' 
  25. sxport default
  26.     methods:{ 
  27.    add(){ 
  28.     this.$store.commit(Increase) 
  29.    } 
  30.   } 

使用的时候,只需要记住 Increase 或者在 mutation_type.js 文件内查找就好了。

责任编辑:姜华 来源: 今日头条
相关推荐

2020-03-18 14:00:47

MySQL分区数据库

2021-06-30 08:45:02

内存管理面试

2022-06-07 10:13:22

前端沙箱对象

2021-07-08 10:08:03

DvaJS前端Dva

2020-12-07 06:19:50

监控前端用户

2019-11-06 17:30:57

cookiesessionWeb

2022-08-19 09:24:46

计算机技术

2022-04-11 10:56:43

线程安全

2023-04-12 08:38:44

函数参数Context

2021-08-05 06:54:05

观察者订阅设计

2023-11-23 06:50:08

括号

2020-12-18 09:36:01

JSONP跨域面试官

2021-01-22 06:35:44

IoCxml驱动技术

2021-01-06 13:52:19

zookeeper开源分布式

2024-04-12 12:19:08

语言模型AI

2020-05-11 14:35:11

微服务架构代码

2022-09-29 10:26:59

iOSScaffoldflutter

2022-03-24 08:51:48

Redis互联网NoSQL

2023-01-27 18:55:37

Python内置函数

2019-12-04 13:50:07

CookieSessionToken
点赞
收藏

51CTO技术栈公众号