vuex 结构图

在这里插入图片描述

vuex 核心概念和 API

1. state

    1. vuex 管理的状态对象
    1. 它应该是唯一的
const state = { 

xxx: initValue 

}

2. mutations

    1. 包含多个直接更新 state 的方法(回调函数)的对象
    1. 谁来触发: action 中的 commit(‘mutation 名称’)
    1. 只能包含同步的代码, 不能写异步代码
const mutations = { 

    yyy (state, {data1}) { 

    // 更新 state 的某个属性 

    } 

} 

3. actions

    1. 包含多个事件回调函数的对象
    1. 通过执行: commit()来触发 mutation 的调用, 间接更新 state
    1. 谁来触发: 组件中: $store.dispatch(‘action 名称’, data1) // ‘zzz’
    1. 可以包含异步代码(定时器, ajax)
const actions = { 

    zzz ({commit, state}, data1) { 

    commit('yyy', {data1}) 

    } 

} 

4. getters

    1. 包含多个计算属性(get)的对象
    1. 谁来读取: 组件中: $store.getters.xxx
const getters = { 

    mmm (state) { 

return ...

5. modules

    1. 包含多个 module
    1. 一个 module 是一个 store 的配置对象
    1. 与一个组件(包含有共享数据)对应

6. 向外暴露 store 对象

export default new Vuex.Store({ 

    state, 

    mutations, 

    actions, 

    getters 

}) 

7. 组件中

import {mapState, mapGetters, mapActions} from 'vuex' 

export default { 

computed: { 

...mapState(['xxx']), 

...mapGetters(['mmm']), 

}

methods: mapActions(['zzz']) 

}

{{xxx}} {{mmm}} @click="zzz(data)" 

8. 映射 store

import store from './store' 

new Vue({ 

    store 

}) 

9. store 对象

    1. 所有用 vuex 管理的组件中都多了一个属性$store, 它就是一个 store 对象
    1. 属性:

state: 注册的 state 对象

getters: 注册的 getters 对象

    1. 方法:

dispatch(actionName, data): 分发调用 action

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐