- 介绍
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
原先数据需要保存到各自vue实例对象的data中,当使用vuex之后,就可以将data中的数据集中管理到vuex中。
vue - data
{
customer:{}
}
-
交互:
双向数据绑定
渲染
事件绑定,事件处理 -
数据维护 (转交-> vuex)
loadData
axios.get()vuex - state
-
数据维护【状态】
Customer.vue
{
customers:[],
visible:false,
}
Category.vue
{
categories:[],
visible:false
}
...
2) 核心概念
1. state 状态,data,用于存储状态
state:{
customers:[]
}
2. getter 获取器,类似于computed,从store 中的 state 中派生出一些状态
getters:{
customersSize:function(){
return customers.length;
},
customersFilter(){
}
}
3. mutation 突变,是vuex中唯一可以修改state值的机制,并且这种修改是同步的,不允许包含异步代码
mutations:{
refreshCustomers(state,customers){
state.customers = customers;
}
}
4. action 动作,是vuex中唯一可以包含异步【异步操作的同步化】操作的机制,但是,action不能直接修改state中的值,但是可以通过提交突变的方式修改state中的值.
actions:{
async findAllCutomers(context){
let response = await axios.get();
context.commit("refreshCustomers",response.data.data)
}
}
3) 深入理解状态机
0 实例化
let store = new Vuex.Store({
state:{},
getters:{},
mutations:{},
actions:{}
})
1. state
1) 作用
维护状态,customers、visible...
2) 定义
state:{
customers:[],
visible:false
}
3)使用
1. 通过状态机实例对象直接访问
store.state.customers
2. 如何在vue实例中访问(通过计算属性映射)
new Vue({
el:"",
store, //注入store
data:{},
computed:{
customers:function(){
return this.$store.state.customers;
}
}
})
2. mutation
1) 作用
唯一修改state值的机制,并且只能是同步操作
2) 定义
state:{
customers:[]
}
mutations:{
refreshCustomers(state,customers){
}
}
state是vuex实例化并且传递给突变,customers属于该突变一个载荷对象(参数)
3) 使用
store.commit("refreshCustomers",[1,2,3])
3. action
1) 作用
封装异步操作,不能直接更新state,必须借助mutation来进行更新
2) 定义
actions:{
async findAllCustomers(context){
let response = await axios.get();
context.commit("refreshCustomers",response.data.data)
},
// id
async deleteCustomerById(context,payload){
let response = await axios.get("",payload);
context.dispatch("findAllCustomers")
}
}
context是一个与store对象解构相似的对象,包含了commit、dispatch、getters、state
3) 使用
store.dispatch(actionName,payload)
4. 模块化
let customer = {
namespaced:true,
state:{
list:[],
visible:false
},
getters:{
},
mutations:{
},
actions:{
}
},
let category = {
namespaced:true,
state:{
list:[],
visible:false
},
getters:{
},
mutations:{
},
actions:{
}
}
let store = new Vuex.Store({
modules:{
customer,
category
}
})
new Vue({
computed:{
...Vuex.mapState("customer",["list"])
}
})