【原创】Vuex

什么是 Vuex

专门在 Vue 中实现集中式管理的一个 Vue 插件,对 Vue 应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且用于任意组件间的通信。

什么时候使用 Vuex

  • 多个组件依赖于同一状态
  • 来自不同组件的行为需要变更同一状态

Vuex 的工作原理

搭建 Vuex 环境

  • npm i vuex
  • Vue.use(Vuex)
import store from './store/index';
new Vue({
el:'#app',
store:store
render:h=>h(App)
})
  • src/store/index.js*
    import Vue from 'vue';
    import Vuex from 'vuex';
    Vue.use(Vuex);
    // 响应组件中的动作
    const actions = {}
    // 操作数据
    const mutations = {}
    // 存储数据
    const state = {}
    const getters = {
    bigSum(state){
    return state.sum * 10;
    }
    }
    // 创建 store 并对外暴露
    export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
    });

单纯调整 import、Vue.use 的顺序不够,即便将 Vue.use 写到 import 之前,vue 也会自动将 import 调整到上方,所以在 store.js 中引入 vuex。

组件中读取 Vue 数据

$store.state.sum

组件中修改 Vuex 中的数据

$store.dispatch('action',data)
$store.mutation('mutation',data)

若没有网络请求或其他业务逻辑,也可以越过 actions,即不写 dispatch,直接写 commit。

getters

当 state 中的数据需要加工之后再使用时,可以使用 getters。state 和 getters 的关系很像 data 和 computed 的关系。
读取:$store.getters.bigSum

4 个 map 的使用

  • mapState:映射 state 中的数据为计算属性
computed:{
...mapState({sum:'sum', school:'school'})
...mapState(['sum','school'])
}
  • mapGetters:映射 getters 中的数据为计算属性
computed:{
...mapGetters({bigSum:'bigSum'})
...mapState(['bigSum'])
}
  • mapActions:生成与 actions 对话的方法,即包含 $store.dispatch() 的函数。
methods:{
...mapActions({incrementOdd:'jiaOdd'})
...mapActions(['jiaOdd','jiaWait'])
}
  • mapMutations:生成与 mutations 对话的方法,即包含 $store.commit() 的函数。
methods:{
...mapMutations({increment:'JIA'})
...mapMutations(['JIA','JIAN'])
}

mapActions 与 mapMutations 使用时,若需传递参数,需要在模板中绑定事件时传递好参数,否则参数是事件对象。

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注