1.什么是Vuex?
官方给的解释是:
Vuex 是一个专为 Vue.js 应用程序开发的**状态管理模式 + 库。**它采用集中式存储管理应用的所有组件的状态。并以相应的规则保证状态以一种可预测的方式发生变化。
这里可以理解为:Vuex也是组件通信的一种,只不过这种通信方式,更强大一些,他可以让所有的组件都可以访问到Vuex里面的数据,就不像子传父,父传子那样看着臃肿
但是如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。
接下来让我们学习一下Vuex:
Vuex的使用步骤
1.下包:yarn add vuex@3.6.2 -S
2.新建src/store/index.js模块
导入vuex/vue
注册
创建实例
导出store实例
3.main.js导入store实例并注入
// 组件内:使用 this.$store 访问store下的核心概念
vuex的5个核心概念
state: 存储共享数据
mutations: 唯一同步修改state
actions: 异步更新state,也必须通过触发mutation函数
getters: vuex的计算属性
modules: 拆模块
vuex的核心概念1 — state
作用:管理共享数据
定义
const store = new Vuex.Store({
state: {
key: value
}
})
使用:
1.直接
this.$store.state.属性名
2.映射
import { mapState } from 'vuex'
computed: {
...mapState([]),
...mapState({})
}
vuex的核心概念2 — mutations
作用:给state的属性赋值(修改)
定义
const store = new Vuex.Store({
mutations: {
函数名(state, 参数) {
// 赋值
}
}
})
使用
1.直接
this.$store.commit('mutation函数名', 值)
2.映射
import { mapMutations } from 'vuex'
methods: {
...mapMutations([ ]),
...mapMutations({ }),
}
vuex的核心概念3 — actions
作用:包装异步操作,最终需要提交到mutation
定义
const store = new Vuex.Store({
actions: {
函数名(store, 参数) {
// 异步操作
// 提交mutation函数
}
}
})
使用
1.直接
this.$store.dispatch('action函数名', 值)
2.映射
import { mapActions } from 'vuex'
methods: {
...mapActions([ ]),
...mapActions({ }),
}
vuex的核心概念4 — getters
作用:vuex(全局)计算属性,基于state计算得到新数据
定义
const store = new Vuex.Store({
getters: {
计算属性名(state) {
return 计算结果
}
}
})
使用
1.直接
this.$store.getters.计算属性名
this.$store.getters['计算属性名']
2.映射
import { mapGetters } from 'vuex'
computed: {
...mapGetters([ ]),
...mapGetters({ }),
}
vuex的核心概念5 — modules
作用:拆模块,划分多个store、共享数据分模块管理
定义
创建子模块对象 - 定义4个核心概念 - 导出子模块
根store -> 导入子模块 -> 注册子模块
const store = new Vuex.Store({
modules: {
子模块1,
子模块2,
...
}
})
// 注意2个点:
// 1. 子模块的state推荐写函数,但写对象也可以
// 2. 子模块需要开启命名空间, 防止同名冲突
使用state
直接
this.$store.state.模块名.属性名
映射
computed: {
...mapState('模块名', [ ]),
...mapState('模块名', { })
}
使用mutations
直接
this.$store.commit('模块名/mutation函数名', 值)
映射
methods: {
...mapMutations('模块名', [ ]),
...mapMutations('模块名', { }),
}
使用actions
直接
this.$store.dispatch('模块名/action函数名', 值)
映射
methods: {
...mapActions('模块名', [ ]),
...mapActions('模块名', { }),
}
使用getters
直接
this.$store.getters['模块名/计算属性名']
映射
computed: {
...mapGetters('模块名', [ ]),
...mapGetters('模块名', { }),
}
注意事项
-
在vue文件中,使用state/mutations/actions/getters都有2种方式
-
但在js文件中,要想使用state/mutations/actions/getters,需要这么做:
-
导入 store 实例
import store from '@/store'
-
通过 store 实例去访问
store.state.属性名 store.commit() store.dispatch() store.getters.计算属性名
-