vuex是vue独立于组件系统之外的状态管理工具,可以实现公共数据共享,跨组件通讯,并且有响应式的特点
新项目创建的时候可以直接自定义vuex,老项目需要下载配置
下载: npm install vuex@3.6.2 使用vue2就下载3的版本,vue3就下载4
vuex有五个方法,跟vue中的功能类似
1.state 作用:统一定义公共数据(类似于data(){return{a:1,b:2}}
定义格式: state:{
变量名:""
};
使用:this.$store.state.变量名
2.mutations 作用:使用它来修改数据(类似于methods),vuex所有数据修改都要通过mutations
定义格式: mutations:{
modName(state,newName){
state.count = newName
}
}
使用:this.$store.commit("modName","小花")
3.getters 作用:类似于computed(计算属性,对现在的状态进行计算得到新的数据
定义格式: new Vuex.store({
getters: {
getter的名字1: function(state) {
return 要返回的值
}
}
})
使用 this.$store.getters.名字
4.actions 作用:发送异步请求
定义格式: new Vuex.store({
actions: {
action的名字: function(context, 载荷) {
}
}
})
this.$store.dispatch('名字',实参)
5.modules 作用:模块拆分,可以将模块放入一个新的文件中,然后引入在modules中注册使用
export default new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {
模块名1: {
namespaced: true,
state: {},
getters: {},
mutations: {},
actions: {},
modules: {}
},
模块名2: {
state: {},
getters: {},
mutations: {},
actions: {},
modules: {}
}
}
})