Vuex使用
2019-11-29 本文已影响0人
blank_lion
model-manage.js
const state = {
classificationObject: [],
activeModel: {}
}
const getters = {
models: state => {
const models = []
state.classificationObject.forEach(classification => {
(classification['bk_objects'] || []).forEach(model => {
models.push(model)
})
})
return models
},
//返回一个函数
getModelById: (state, getters) => id => {
return getters.models.find(model => model['bk_obj_id'] === id)
},
}
const mutations = {
setActiveModel(state, model) {
state.activeModel = model;
},
setClassificationObject(state, classificationObject) {
state.classificationObject = classificationObject;
}
}
const actions = {
//返回promise
findClassificationObject({ commit }) {
return $api.bkApi.findClassificationObject().then(response => {
commit('setClassificationObject', response);
return response;
});
}
}
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
main.js:
import modelManage from './modules/views/model-manage.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
modelManage
}
})
使用state:
var objectData = this.$store.state.modelManage.classificationObject;
var activeModel = this.$store.state.modelManage.activeModel;
computed: {
...mapState({
modelId: state => state.modelManage.activeModel.bk_obj_id,
modelName: state => state.modelManage.activeModel.bk_obj_name
})
},
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
使用mutations
this.$store.commit("modelManage/setActiveModel", model);
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
使用getter
...mapGetters({
getModelById: "modelManage/getModelById"
}),
const model = this.getModelById()(this.$route.params.modelId);
const model = this.$store.getters["modelManage/getModelById"](
this.$route.params.modelId );
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
使用action
...mapActions({
findClassificationObject: "modelManage/findClassificationObject"
}),
await this.findClassificationObject();
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
组合 Action
(https://vuex.vuejs.org/zh/guide/state.html)