使用vue+webpack构建项目(三) Vuex中的 mutation和action

知识点复习

使用vue+webpack构建项目(二) 引入vuex vue-resource vue-router

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation

// 区别

  • mutation 必须同步执行
  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

在组件中使用

  • this.$store.commit(type, payload) 来调用mutations中的函数
  • this.$store.dispatch(fun) 来调用actions中的函数

使用:

  • 如果是同步操作,那么直接在页面中调用 mutations函数就可以。
  • 如果需要异步操作,则需要在组件中调用actions方法。

只能通过mutations 改变状态,所以即使是使用了actions,也需要用action来提交mutations

学习 vuex mutation

在 list/index.vue中

// 在methods 中使用 mapMutations 来执行 同步的方法
methods: { 
    ...mapActions({   
        // add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
        getData: 'actionItems'
    }),
+   ...mapMutations({
+       // add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
+       addFun: 'changeNum'
+   })
} 

在 store/modules/list.js 中


const mutations = {
  // state 当前state
  // aa 自定义参数
  async getItems (state, aa) {
    const result = await ajax('https://www.easy-mock.com/mock/5c24adb39a96a934e48de313/api/douban/movie/top', {
        method: 'get',
        data: {}
    })
    state.items = result.data.movie
    console.log(state.items)
  },
+ changeNum (state, payload) {
+   state.changeNum = payload * payload
+ }
}

// actions 的内容不需要改变,因为 mutations 中是同步操作,直接使用mutations来改变状态就可以了

在这里插入图片描述
ps:

关注我获取更多前端资源和经验分享
在这里插入图片描述

感谢大佬们阅读,希望大家头发浓密,睡眠良好,情绪稳定,早日实现财富自由~

发布了102 篇原创文章 · 获赞 202 · 访问量 40万+

猜你喜欢

转载自blog.csdn.net/zr15829039341/article/details/91592291