vuex

245 阅读1分钟

vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件的公共状态, 并以相应的规则保证状态以一种可预测的方式发生变化.

结构图

如何引入Vuex

下载:npm install vuex --save

同一个文件引用

Vue.use( Vuex );
const store = new Vuex.Store({
    //待添加
})
new Vue({
    el: '#app',
    store,
    render: h => h(App)
})

全部抽离成单个文件

index.js

/*
vuex最核心的管理对象
*/
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
Vue.use(Vuex)
export default new Vuex.Store({
 state,
 mutations,
 actions,
 getters
})

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
new Vue({
 el: '#app',
 router,
 components: { App },
 template: '<App/>',
 store
})

单文件引用

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

Vue.use(Vuex)
// 首先声明一个状态 state
const state = {
count: 0
}

// 然后给 actions 注册事件处理函数,当这个函数被触发时,将状态提交到 mutaions中处理
const actions = {
increment: ({ commit }) => commit('increment'), // 提交到mutations中处理
decrement: ({ commit }) => commit('decrement')
}
// 更新状态
const mutations = {
increment (state) {
  state.count = state.count + 5
},
decrement (state) {
  state.count = state.count - 3
}
}
// 获取状态信息
const getters = {
}

// 下面这个相当关键了,所有模块,记住是所有,注册才能使用
export default new Vuex.Store({
state,
mutations,
actions,
getters
})

核心

state

  • vuex管理的状态对象
  • 它应该是唯一的

mutations

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

actions

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

getters

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

调用

  • mapState,mapGetters,mapActions来调用
computed:{ ...mapState(['xxx']), ...mapGetters(['mmm']), } methods:mapActions(['zzz'])

+使用 store.state,store.dispatch('action 名称',data1)来调用