zoukankan      html  css  js  c++  java
  • vue-vuex-actions的基本使用

      之前也讲过了,actions中是用来操作异步代码的,由于在mutations写异步操作会导致devtools工具记录不到state的变化,因此才有actions的存在,下面是基本的使用,如下:

      点击按钮,发布到actions:

    <template>
      <div>
        <button @click="toAjax">发起异步请求</button>
      </div>
    </template>
    
    methods: {
        toAjax(){
          this.$store.dispatch('sendAjax')
        }
      }

      定义sendAjax,并提交到mutations:

      mutations: {
        msendAjax(state){
          state.counter++
        }
      }
      actions: {
        sendAjax(context){
            //异步操作
          setTimeout(()=>{
            context.commit('msendAjax')
          },1000)
        }
    
      }

      上面的context对象相当于state,拥有一些和state相同的方法。上面只是基本的使用,如果在dispatch要传递参数,和commit传递参数要怎么做呢?如下:

     methods: {
        toAjax(){
          const arg = '我是参数'
          this.$store.dispatch('sendAjax',arg)
        }
      }
     
      mutations: {
        msendAjax(state,payload){
          console.log(payload)
          state.counter++
        }
      },
      actions: {
        sendAjax(context,arg){
          setTimeout(()=>{
            context.commit('msendAjax',arg)
          },1000)
        }
      }

      上面是actions无参和有参的基本使用了。但实际开发中,在actions中方法执行完毕了,要给componnet返回结果告诉操作已经完成,那该如何做呢? 如下:

    <template>
      <div>
        <button @click="toAjax">发起异步请求</button>
      </div>
    </template>
    methods: {
        toAjax(){
          const arg = '我是参数'
          this.$store
          .dispatch('sendAjax',arg)
          .then(() => {
            console.log('dispatch已经完成了')
          })
        }
      }
      mutations: {
        msendAjax(state,payload){
          console.log(payload)
          state.counter++
        }
      },
      actions: {
        sendAjax(context,arg){
          return new Promise(resolve => {
            setTimeout(()=>{
              context.commit('msendAjax',arg)
              resolve()
            },1000)
          })
        }
      }

      参数该怎么传还怎么传,原本的异步代码用 new Promise包裹起来,然后.then不要在actions中写,在components写会比较明显易懂

  • 相关阅读:
    类 7.2访问控制与封装 笔记
    第七章 类(class)7.1 笔记
    10.4.3反向迭代器Reverse_iterator笔记
    10.4再探迭代器笔记
    10.3.4参数绑定 bind
    10.3lambda表达式笔记
    第10章 10.1-10.3笔记
    关于按下ctrl+z后,之后的cin失效的问题
    构造和改变一个string的其他方法
    BZOJ2527 & 洛谷3527:[Poi2011]Meteors——题解
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14641350.html
Copyright © 2011-2022 走看看