Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式, 采用集中式存储管理应用的所有组件的状态,解决多组件数据通信。
- vuex是vue官方提供的独立于组件体系之外的,管理公共数据的工具
- 五个概念:state, mutations, getters, actions, modules
在旧项目中使用vuex
-
1 安装。它是一个独立的包,需要先安装。
-
2 配置 store/index.js: . 创建Vuex.Store实例 . 向Vue实例注入store
-
3 使用。在组件中使用store
进入项目目录,安装包 npm install vuex
- 在store/index.js 中放置具体的代码,具体如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
}
})
export default store
-
向Vue实例注入store
// 省略其他
// 1. 导入store
import store from './store'
new Vue({
// 省略其他...
store // 2. 注入Vue实例
})
在组件中使用store:在任意组件中,通过this.$store.state 来获取公共数据。
Vuex-state定义公共数据并在组件中使用
- state的作用: vuex用它来保存公共数据 格式:
new Vuex.store({
state: {
属性名: 属性值
}
})
- 在组件中,通过
this.$store.state.属性名来访问。 - 映射是在 组件的computed中 映射语法如下:import { mapState } from "vuex"; 引入后 在 computed中 ...mapState(['xxxx]) 使用直接 {{xxxx}}
Vuex-用mutations修改公共数据
- mutations 可以用来修改 state中的数据, 通过调用mutations来修改定义在state中的公共数据。
- 定义格式: 如下
mutations:{
// 每一项都是一个函数,可以声明两个形参
函数名(state,参数){
}
- 使用格式
- 1在组件中是 this.$store.commit('函数名',实参 给第二个参数 注意!!!只能传一个参,可以写成 对象 数组形式 ) 如果写成 对象数组形式 接收时可以用 对象解构 {m,n} 来操作数据
- 2 使用映射: 先引入 import { mapState,mapMutations } from "vuex";
注意写在 methods中 ...mapMutations(['函数名']) 使用时 this.函数名()
注意不能在组件内部直接修改 state中数据,在严格模式下会报错,想更改state中的数据,必须得通过mutations来进行更改
Vuex-用getters的派生状态
- 在state中的数据的基础上,进一步对数据进行加工得到新数据。(与组件中computed一样)
- 格式 如下:
getters:{
函数名(state){ return: 加工操作返回值 }
}
- 在组件中使用方法 :this$store.getters.函数名
- 映射方法 在组件中先引入: import { mapState,mapMutations,mapGetters } from "vuex"; 在computed中 ...mapGetters(['函数名']) 使用时 {{函数名}}
Vuex用actions发异步请求
我们可以使用Action来修改state,这一点是类似于 mutation的,不同在于:
- action中可以通过调用 mutation来修改state,而不是直接变更状态。
- action 可以包含任意异步(例如ajax请求)操作。
- 定义格式如下:
actions: {
// context对象会自动传入,它与store实例具有相同的方法和属性
action的名字: function(context, 载荷) {
// 1. 发异步请求, 请求数据
// 2. commit调用mutation来修改/保存数据
// context.commit('mutation名', 载荷)
}
}
注意第一个形参中 有很多方法 其中commit方法 可以用 context.commit('mutations中函数名',参数) 来使用
- 使用方法: 组件中使用 this.$store.dispatch('函数名')
- 映射方法 引入步骤同上,写在methods中 ...mapActions(['函数名']) this.函数名()
Vuex-用modules来拆分复杂业务
modules的作用
拆分模板,把复杂的场景按模块来拆开
-
在store文件夹中 新建文件夹modules文件夹 在下面新建文件,然后写入格式如下:
export default {
namespaced: true,
state: {},
mutations: {},
getters: {},
actions: {}
}
在store 中 index.js文件夹中 先引入 然后在 modules: { } 中挂载 引入定义名字建议和挂在名字一样 这样可以简写
- namespaced:true // 只要分模块这行代码就加上
- state
- $store.state.模块名.属性名
- ...mapState(‘模块名’,['xxxx]) ====={{xxx}}
- mutations
- $store.commit('模块名/函数名')
- ...mapMutations(‘模块名’,['xxxx']) this.xxxx()
- actions
- $store.dispatch('模块名/函数名')
- ...mapActions(‘模块名’,['xxxx']) this.xxxx()
- getters
- $store.getters['模块名/函数名']
- ...mapGetters(‘模块名’,['xxxx]) ====={{xxx}}
-
注意在 组件中使用时 需要加上模块名 getters比较特殊 getters['模块名/函数名']注意一下