前端培训-中级阶段(41)- vue 2.x 状态管理 vuex
码农天地 -前端最基础的就是 HTML+CSS+Javascript
。掌握了这三门技术就算入门,但也仅仅是入门,现在前端开发的定义已经远远不止这些。前端小课堂(HTML/CSS/JS
),本着提升技术水平,打牢基础知识的中心思想,我们开课啦(每周四)。
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
五大核心模块State,数据中心,可以理解为 Vue 中的 data。只不过为了保持数据流向,需要用 store.commit('increment')
来修改(Mutation 内部再去修改 state),可以更明确地追踪到状态的变化。
store.state.count
、this.$store.state.count
、mapState
mapState 可以接收对象和数组,可以直接放在 computed: mapState({})
上,也可以使用展开运算符 computed: {localComputed () {}, ...mapState({})}
对象形式
mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
数组形式
mapState([
// 映射 this.count 为 store.state.count
'count'
])
Getter,可以理解为 Vue 的 computed 计算属性,返回值也会根据它的依赖被缓存起来,只有当它的依赖值发生了改变才会被重新计算。
获取时可以使用store.getters.count
、this.$store.getters.count
、mapState
mapGetters
单纯的映射...mapGetters(['doneTodosCount','anotherGetter',])
换个名字映射出来 ...mapGetters({doneCount: 'doneTodosCount'})
Mutation 可以理解为methods ,也可以理解为 setState ,只不过 mutation 必须是同步函数,定义上来说是用来同步修改 state。
store.commit('increment')
不传递内容 increment (state, payload){payload == undefined}
store.commit('increment', 1)
传递数值 increment (state, payload){payload == 1}
store.commit('increment', {n:1})
传递对象(推荐) increment (state, payload){payload == {n:1}}
(我只是在描述内容是什么,想测试可以用 console.log)...mapMutations(['increment'])
...mapMutations({add:'increment'})
将 this.add()
映射为 this.$store.commit('increment')
在 vue 中使用
mapActions
做快捷映射,也可以不做映射直接使用 store.dispatch('increment')
。dispatch
会返回一个 Promise
,所以我们也可以愉快的监听异步是否执行完成。Module Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {
namespaced: true,//通过namespaced开启命名空间,默认情况下,模块内部的 action、mutation 和 getter 是注册在**全局命名空间**的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
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 的状态
微信公众号:前端linong参考文献前端培训目录、前端培训规划、前端培训计划