vuex简介

307 阅读1分钟

vuex是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式, 采用集中式存储管理应用的所有组件的状态,解决多组件数据通信

一 . 使用方式

import Vuex from "vuex"
//引入 modules 拆分模块
import books from "./modules/book"

Vue.use(Vuex)
export default new Vuex.Store({
    state: {},
    mutations: {},
    getters: {},
    actions: {},
    modules: {
        books
    }
})

modules 拆分模块

import axios from "axios";

export default {
    namespaced: true,
    state: {
        book: [],

    },
    mutations: {
        // 修改原数据
        upDataBooks(state, books) {
            state.book = books
        }
    },
    actions: {
        // 发送请求
        newbooks(context) {
            axios({
                method: 'get',
                url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books'
            }).then(res => {
                console.log(res);
                context.commit('upDataBooks', res.data.data)
            })
        }
    },
    getters: {
        // 计算价格总和
        getPrice(state) {
            return state.book.reduce((sum, obj) => {
                return sum + obj.price
            }, 0)

        }
    },

}

小结:

1. actions和mutations和state的关系图

vuex.png

2. 核心API

vuex核心.png

3 . Vuex-map函数用法汇总

如何使用全局state

  • 直接使用: this.$store.state.xxx;
  • map辅助函数:
computed: { 
  ...mapState(['xxx']), 
  ...mapState({'新名字': 'xxx'})
}

如何使用modules中的state

  • 直接使用: this.$store.state.模块名.xxx;
  • map辅助函数:
computed: { 
  ...mapState('模块名', ['xxx']), 
  ...mapState('模块名', {'新名字': 'xxx'})
}

如何使用全局getters

  • 直接使用:this.$store.getters.xxx

  • map辅助函数:

    computed: { 
      ...mapGetters(['xxx']), 
      ...mapGetters({'新名字': 'xxx'})
    }
    

如何使用modules中的getters

  • 直接使用: this.$store.getters.模块名.xxx

  • map辅助函数:

    computed: { 
      ...mapGetters('模块名', ['xxx']), 
      ...mapGetters('模块名',{'新名字': 'xxx'})
    }
    

如何使用全局mutations

  • 直接使用:this.$store.commit('mutation名', 参数)

  • map辅助函数:

    methods: { 
      ...mapMutations(['mutation名']), 
      ...mapMutations({'新名字': 'mutation名'})
    }
    

如何使用modules中的mutations(namespaced:true)

  • 直接使用: this.$store.commit('模块名/mutation名', 参数)

  • map辅助函数:

methods: { 
  ...mapMutations('模块名', ['xxx']), 
  ...mapMutations('模块名',{'新名字': 'xxx'})
}

如何使用全局actions

  • 直接使用:this.$store.dispatch('action名', 参数)

  • map辅助函数:

methods: { 
  ...mapActions(['actions名']), 
  ...mapActions({'新名字': 'actions名'})
}

如何使用modules中的actions(namespaced:true)

  • 直接使用: this.$store.dispatch('模块名/action名', 参数)

  • map辅助函数:

methods: { 
  ...mapActions('模块名', ['xxx']), 
  ...mapActions('模块名',{'新名字': 'xxx'})
}