vuex的使用

 

State

1、概念:state提供唯一的公共数据源,所有的共享数据都要统一放到store的state中进行存储

state: {
 count: 0
},

2、组件访问State中数据的方式:

this.$store.state.全局数据名称

Mutations

1、概念:Mutations用于变更store中的数据。

(1)只能通过mutation变更store数据,不可以直接操作store中的数据

(2)通过这种方式虽然操作起来稍微繁琐点,但是集中监控所有数据的变化更方便

(3)mutation只能执行同步操作,想要执行异步变更数据需要用到action

2、定义mutation


mutations: {
 //1.定义没有参数的方法  
 //state参数代表全局的state数据对象
 add(state,){
     //变更状态
    state.count ++
},
      //2.定义有参数的方法 
     //第一个参数是state数据对象,第二个参数是行参
     addN(state,step){
     state.count += step
  },
}

3、调用mutation

methods: {
   //1.调用不传参数的mutation方法
   but() {
     // this.$store.commit() 调用全局vuex里面mutations里面定义的函数
     this.$store.commit('add')
  },
   //2、调用传参数的mutation方法    
    but1() {
        let count 3
        this.$store.commit('addN',count)
  },        
}

actions

1、概念:acction用于处理异步任务

(1)如果通过异步操作变更数据,必须通过action,而不是Mutation,但是在action中还是要通过触发mutation的方式间接来变更数据

2、定义action

actions: {
   //context是上下文参数对象
 addAsync(context){
   setTimeout(()=>{
       //这里还是通过调用mutation的方法来执行数据变更
     context.commit('add')
  },1000)
}
},

3、调用action

but3(){
   // this.$store.dispatch() 就是调用actions里面的方法
   this.$store.dispatch('addAsync')
}

getters

1、getter用于对store中的数据进行加工处理形成新的数据

(1)getter不会改变原来的state数据

(2)state数据发生变化,getter数据也会发上变化

2、定义getter

getters: {
 showNum(state){
   return "当前最新的数量是【"+state.count++"】"
}
},

3、调用getter

this.$store.getters.定义的getter数据名称

Modules

1、存放定义的vuex模块

posted @ 2022-02-10 16:26  壮灬哥  阅读(31)  评论(0编辑  收藏  举报