Vuex(篇3)——actions

Action中还是要通过触发Mutation的方式间接变更数据。

actions中定义的方法,都会有默认值context

  • context是和store对象具有相同方法和属性的对象
  • 可以通过context进行commit相关操作,可以获取context.state数据

vuex中定义异步函数(不传参)

vuex中定义actions

 mutations: {
        add(state){
            state.count++
        },
        addN(state,payload){
            this.state.count+=payload.number
        }
    },
    actions: {
        addAsync(context){
            setTimeout(() => {
                context.commit('add')
            },5000)
        }
    }

组件中使用

方式1:组件中在methods中调用

<button @click="add">点击添加1</button>
add() {
    this.$store.dispatch('addAsync')
}

方式2:在组件中,导入mapActions函数

通过刚才导入的mapActions函数,将需要的actions函数映射为当前组件的methods方法


import {mapActions} from 'vuex'
...mapActions(['addAsync'])
addCount() {//一种写法
     this.addAsync()        
}

//另一种写法
<button @click="addAsync">点击</button>

vuex中定义异步函数(传参)

vuex中定义actions

addNAsync(context,payload){
            setTimeout(() => {
                context.commit('addN',payload)
            },3000)
}

vue组件中调用

//方式1
 addCountN() {
            this.$store.dispatch('addNAsync',{
                number:8
            })
        }
//方式2
 addCountN() {
            this.addNAsync({number:7})
        }

actions与Promise结合使用

loadInfo(context){
            return new Promise((resolve) => {
                setTimeout(() => {
                    context.commit('add')
                    resolve()
                },2000)
            })
        }

组件中调用

add() {
          this.$store.dispatch('loadInfo').then((res) => {
              console.log(res,'hello')
          })
      }

猜你喜欢

转载自blog.csdn.net/weixin_40119412/article/details/107595484