一、概念
在vue中实现集中式状态 (数据) 管理的插件, 对于vue中多个组件共享的状态进行集中式的管理(读写操作),也是一种组件通信方式,适用于任意组件。vuex采用单一状态树,强调唯一数据源,响应式
1. 什么时候使用Vuex:
- 多个组件依赖同一个状态
- 来自不同组件的行为需要变更同一状态
二、使用
1.安装版本
- vue2 使用的是 Vuex3
- vue3 使用的是 Vuex4
2.vue cli
- 在src 目录下创建名为 store的文件夹, 并创建名为index.js的文件
- store 的作用主要是管理 Actions , Mutations , State 三个对象
State用于存储数据的的容器对象Mutations用于操作(写)数据的对象Actions用于调用 mutations(异步)getters用于监听 state 值的变化,相当于是 state 的计算属性
import Vuex from 'vuex';
Vue.use(Vuex);//把store绑定到vue.prototype上
const store=new Vuex.Store({
// 数据
state:{
count:o;
},
// 操作数据的 api
mutations:{
increment(store){
store.count+=1;
}
},
})
export default store
import store form ‘xxx’
thix.$store.state.count
//使用mutations,需要使用commit
this.$store.commit('increment')
//使用actions里的方法
this.$store.dispatch('xxx')
//如果在组件中想获取Vuex中的数据,最好使用computed,因为是响应式的
computed:{
count(){
return store.state.count;
}
}
//使用了vue.use后,就可以通过this调用
this.$store.commit(increment)
三、实际使用
- 将多个组件都使用的数据 保存在
vuex的state中 - 在 Actions 中封装异步操作,与数据库交互数据,然后调用mutations,修改state