我有几个组件,都需要用到vuex.store,而且这几个组件结构极其类似,就在想,能不能复用store的对象定义?因为每个组件都定义一遍,繁琐,且没必要。
主要是用到克隆组件。具体代码如下:
1)共用的store定义
/src/store/common.js
export default {
namespaced: true,
state: {
v: "hello store", // for test
items: [],
},
getters: {
v: (state) => state.v,
items: (state) => {
return state.items;
},
},
mutations: {
// 同步操作
setV(state, val) {
state.v = val;
},
setItems(state, val) {
state.items = val;
},
},
actions: {
keepItems: ({ commit }, val) => {
commit("setItems", val);
},
},
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
2)组件1
/src/store/component1.js
import cloneDeep from "lodash/cloneDeep";
import common from "./common";
const category = cloneDeep(common);
export default component1;
- 1
- 2
- 3
- 4
- 5
- 6
3)组件2
/src/store/component2.js
import cloneDeep from "lodash/cloneDeep";
import common from "./common";
const category = cloneDeep(common);
export default component2;
- 1
- 2
- 3
- 4
- 5
- 6