Vuex核心概念
什么是Vuex?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
Store仓库
在 src目录下有一个store文件夹,文件夹下有一个index.js文件,这就是我们的仓库文件,在该文件我们统一进行数据管理。
store的引入
import store from './store/index';
new Vue({
el: '#app',
router,
store,
render: h => h(App)
核心概念
State
state提供唯一的公共数据源,所有共享的数据都要统一放到index.js中的state中进行存储。
export default new Vuex.Store({
state: {
students : [
{ name : "张三",age : 18 },
{ name : "李四",age : 20}
]
}
})
在组件中访问state中的数据
computed: {
getStudent() {
// this.$store 指向 store.js
return this.$store.state.students;
}
}
Getters
我们可以将对仓库值的修改统一写在getter所对应的函数中
getters: {
state: {
students : [
{ name : "张三",age : 18 },
{ name : "李四",age : 20}
]
},
getStuList(state) {
return state.students.map(item => {
return {
name: item.name,
age: item.age * 2
}
});
}
},
在组件中引入
computed: {
getStudent() {
// 通过 this.$store.getters 获取修正后的数据
return this.$store.getters.getStuList;
}
}
Mutations
mutations帮助我们更改Vuex的store中的状态, 每个 mutation 都有一个字符串的事件类型 (type) 和 一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
const store = new Vuex.Store({
state: {
count: 1;
},
mutations: {
addNumber (state, n) {
// 变更状态
state.count += n;
}
}
})
当触发一个类型为addNumber的mutation时,调用此函数,你需要使用到store.commint方法:
store.commit('addNumber', 2);
Actions
Action类似于Mutation,但是不同的是:
-
Action 提交的是 mutation,而不是直接变更状态。
-
Action 可以包含任意异步操作。
注册Acitons
const store = new Vuex.Store({
state: {
count: 1;
},
mutations: {
addNumber (state) {
state.count++;
}
},
actions: {
add (context) {
context.commit('addNumber ');
}
}
});
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用context.commit提交一个 mutation,或者通过context.state 和context.getters来获取 state 和 getters。
actions: {
addNumber ({ commit }) {
commit('addNumber ');
}
}
分发Actions
// 通过store.dispatch方法触发
store.dispatch('addNumber');
Actions 支持同样的载荷方式和对象方式进行分发
// 以载荷形式分发
store.dispatch('addNumber', {
count: 10
});
// 以对象形式分发
store.dispatch({
type: 'addNumber',
count: 10
});
Modules
Vuex允许我们将store分割成模块(module)。 每个模块拥有自己的 state、getters、mutations、actions甚至是嵌套子模块。
const moduleA = {
state: () => ({ ... }),
getters: { ... },
mutations: { ... },
actions: { ... }
}
const moduleB = {
state: () => ({ ... }),
getters: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态