Vuex(五)--Vue核心概念actions

Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state context.getters 来获取 state getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

    /** 
     * 1) 包含多个事件回调函数的对象 
     * 2) 通过执行:commit()来触发 mutation 的调用, 间接更新 state 
     * 3) 包含异步代码(定时器,ajax)和逻辑代码
     * 4) 谁来触发: 组件中:$store.dispatch('action 名称',data1) 
    */

代码实例

store.js

    actions: {
        // content:理解为上下文
        // 商品半价
        disCount (content) {
            // actions中通过commit()提交mutations中的goodsPriceHalve()函数
            content.commit('goodsPriceHalve')
        },
        // 异步的商品半价
        /** 对content进行解构
         * disCountAsync ({commit}){
            setTimeout(() => {
                commit('goodsPriceHalve')
            },1000)
        } */
        disCountAsync ({commit}){
            setTimeout(() => {
                commit('goodsPriceHalve')
            },1000)
        },
        // 统一修改商品名字
        /* acyionChangeName()的第一个参数可以理解成是一个对象,第二个参数为事件传递过来的参数
        这个参数也需要传递给mutations中相对应的函数中*/
        acyionChangeName(content,payload){
            // 载荷形式
            content.commit('changeName',payload);
        },
        acyionChangeNameAsync (content,payload){
            setTimeout(() => {
                // 对象形式
                content.commit('changeName',payload.payload)
            },1000)
        }
    }

这里有同步也有异步,有载荷也有没有载荷。


page7.vue

<template>
    <div>
        <h2>我是第五个页面</h2>
        <div>
            <input type="text" placeholder="请输入商品的新名字" v-model="inpValue">
            <button @click="disCountPrice()">同步商品价格减半</button>
            <button @click="disCountPriceAsync()">异步商品价格减半</button>
        </div>
        <ul class="ul_list">
            <li v-for="item in goodsListHalv">
                <p class="name">商品:{{item.name}}</p>
                <p class="price">价格:¥{{item.price}}</p>
            </li>
        </ul>
    </div>
</template>
<script>
  export default {
     data() {
        return {
            inpValue:'',
        }
      },
      computed: {
          goodsListHalv(){
              return this.$store.state.goodsList;
          }
      },
      methods: {
        //   注意这里使用箭头函数可能会报错
        // 同步商品价格减半;触发事件提交actions中的disCount()函数
          disCountPrice: function(){
              this.$store.dispatch('disCount')
          },
          // 异步商品价格减半
          disCountPriceAsync: function(){
              this.$store.dispatch('disCountAsync')
          },
      }
   }
</script>

page8.vue

<template>
    <div>
        <h2>我是第六个页面</h2>
        <div>
            <input type="text" placeholder="请输入商品的新名字" v-model="inpValue">
            <button @click="acyionChangeName()">载荷修改商品的名字(字符串)</button>
            <button @click="acyionChangeNameAsync()">载荷修改商品的名字(对象)</button>
        </div>
        <ul class="ul_list">
            <li v-for="item in goodsListHalv" :key="item.id">
                <p class="name">商品:{{item.name}}</p>
                <p class="price">价格:¥{{item.price}}</p>
            </li>
        </ul>
    </div>
</template>
<script>
  export default {
     data() {
        return {
            inpValue:'',
        }
      },
      computed: {
          goodsListHalv(){
              return this.$store.state.goodsList;
          }
      },
      methods: {
        //   注意这里使用箭头函数可能会报错
        // 同步修改商品的名字;触发事件提交actions中的acyionChangeName()函数
          acyionChangeName: function(){
              this.$store.dispatch('acyionChangeName',this.inpValue)
          },
          // 异步修改商品的名字;对象 对象中包含两个属性type事件函数,payload参数
          acyionChangeNameAsync: function(){
              this.$store.dispatch({
                  type:'acyionChangeNameAsync',
                  payload:this.inpValue
              })
          },
      }
   }
</script>

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作。
Actions 支持同样的载荷方式和对象方式进行分发。

效果图

代码执行过程:

上面的Action执行过程是:按钮点击–>执行按钮点击事件方法–>执行$store.dispatch('avtions中的对应的函数名',参数)–>执行actions里面对应的方法–>执行mutations里面对应的方法–>修改state里面对应的数据–>页面渲染。

也可以同mutations一样使用常量代替事件类型(更好的管理了事件的名称,使事件名称一目了然) 

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
 
const store = new Vuex.Store({
  state: { ... },
  actions: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    someAction({commit}) {
      commit(SOME_MUTATION)
    }
  }
})

Vuex(四)--Vue核心概念mutations(唯一可以更改vuex实例中state数据状态的属性对象)_muzidigbig的博客-CSDN博客

异步修改状态并修改视图

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    obj: {
      name: 'muzidigbig'
    }
  },
  actions: {
    // 异步修改状态并出发视图
    objAddAge(context, payload) {
      // context.state.obj.age = payload
      context.state.obj.name = "xiaohong";
      // 动态添加状态并修改视图
      Vue.set(context.state.obj, 'age', payload);
      // 动态删除状态并修改视图
      Vue.delete(context.state.obj,'name');
    }
  },
  modules: {
  }
})

模块中

  mounted() {
    this.$store.dispatch.objAddAge(this.age);
  },

在组件中分发 Action

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

注入到methods中

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}


// 直接this.incrementBy(params)使用

总结:

Mutation中我们组件调用方法使用的是commit,在Action中组件使用的却是dispatch分发。看过vue1.x文档的,可能对commit和dispatch就有点感觉了,或者你看过socket。
这里主要要明白以下几点:
1.Mutation是同步的,Action是异步的;
2.Mutation是直接变更状态,Action提交的是mutation(action函数中接受一个同store实例一样的对象content)
3.ActionsMutation 都支持载荷方式和对象方式进行分发。
 

补充知识:

1.mutations 与Actions的区别

首先action与mutation都可以改变state中数据的状态,但是action可以处理异步函数可以在devtools中追踪数据变化,而mutation只可以处理同步函数,当处理异步函数的时候检测不到数据变化

那么是否有人好奇,为什么mutation进行异步操作的时候,为什么页面发生变化了,但是devtools中为什么检测不到数据的变化,而action为什么就可以呢?

下面我们就来探索一下:

为什么mutation必须是同步函数,actions 可以处理异步函数

mutations:{
   someMutation (state) {
      api.callAsyncMethod(() => {
        state.count++
       })
   }
}

如果我们在mutation中写了异步,commit在触发mutation事件时,异步的回调函数不知道是什么时候执行的,所以在devtools中难以追踪变化

actions 可以做异步操作,但是并不是直接修改数据,而是通过提交mutations 里面的方法

actions: {
  setStoreData ({ commit }) {
    mockData().then((res)=>{
        commit('storeData',res)
      })
    }
},
 
mutations:{
 storeData(state,payload){
    state.data = state.data.concat(payload)
   }
}

在页面中触发actions

methods:{
    handleData(){
        this.$store.dispatch('setStoreData')
    }
}

参考文献:链接

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序中管理和维护状态,例如用户信息、购物车、主题等。Vuex将状态存储在一个集中的存储库中,称为storeVuex核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store中获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序中使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件中使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例中,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store中获取count状态。在Vue组件中,我们使用mapGetters和mapActions帮助程序将getter和action映射到组件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值