# vuex
😃
how to use
- 新建一个store.js
import vuex from 'vuex' import vue from 'vue' vue.use(vuex) const state = { count: 0, } const mutations = { //...logical change your state to_mutation(state, payload){ state.count = 23333 } } const actions = { //... async await commit('to_mutation',data) } const getters = { //... count: state => state.count, } export default new vuex.Store({ state, mutations, actions, getters })
- app.js
import store from './store' const app = new Vue({ store //...拼写不要错 })
- 页面使用
{{$store.state.count}} or store.dispatch('name',..)
# The basic
其实等于把一些公共变量放进一个菜篮子里,更改和使用都通向这个菜篮子,而不是父传子传子...
components
-(dispatch) ->> actions
-(commit) ->> mutations
->(mutate)->> state
->(render)-->compoents
state
- 是vuex的唯一的状态对象
- 只读
- this.$store.state.xx
getters
- 可以认为是 store 的计算属性
- 对获取的数据加工
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
mutation
- 直接更新state的对象(更新state的某个属性))
- 接受 state 作为第一个参数
- 同步
// 组件页面
store.commit('increment');
//vuex里
mutations: {
increment (state) {
// 变更状态
state.count++
}
- 不能异步
actions
- 包含多个回调函数的对象
- 也是要
commit
间接变更状态 - 可异步, 用async/await封装
// 页面里
store.dispatch('incr_action');
// store里
actions: {
const actions = {
incr_action(context) {
context.commit('increment')//mutation里
}
}
}
module
- 将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
# 原理
<template>
<div>
count {{$store.state.count}}
</div>
</template>
// as
class Store{
get state () {
return this._vm._data.$state
}
}
- In the lifecycle
beforeCreate
, every component(as vue instance) have mixin the sameStore
as its property$store
, that's reason why we could throughthis.$store.dispatch
to do everything