vuex——为了解决多组件共享状态的问题
状态自管理应用
state: 驱动应用的数据源view: 以声明方式将 state 映射到视图actions: 响应在 view 上的用户输入导致的状态变化(包含 n 个更新状态的方法)
下载: npm install vuex --save
vuex的属性store拥有多个对象
vuex管理的状态对象——state
const state
= {
xxx
: initValue
}
包含多个直接更新state的方法(回调函数)的对象——mutations
const mutations
= {
yyy (state
, data
) {
}
}
包含多个事件回调函数的对象——action
const actions
= {
zzz ({commit
, state
}, data1
) {
commit('yyy', data2
)
}
}
包含多个计算属性(get)的对象——getter
const getters
= {
mmm (state
) {
return ...
}
}
使用vuex
1.store.js
import Vuex
from 'vuex'
export default new Vuex.Store({
state
,
mutations
,
actions
,
getters
})
2.main.js
import store
from './store.js'
new Vue({
store
})`
store对象之间的联系
在组件使用store对象
方法一
所有用vuex管理的组件中都多了一个属性$store, 它就是一个store对象属性:
state: 注册的state对象
this.$store
.state
.nnn
getters: 注册的getters对象
this.$store
.getters
.mmm
方法:
dispatch(actionName, data): 分发action
this.$store
.dispatch("yyy");
方法二
{{xxx}} {{mmm}} @click="zzz(data)"
import {mapState
, mapGetters
, mapActions
} from 'vuex'
export default {
computed
: {
...mapState(['xxx']),
...mapGetters(['mmm']), }
methods
: mapActions(['zzz'])
}
当然啦最好是官网的资源la
github在线文档