debian-mirror-gitlab/app/assets/javascripts/vuex_shared/bindings.js

39 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-03-13 15:44:24 +05:30
/**
* Returns computed properties two way bound to vuex
*
* @param {(string[]|Object[])} list - list of string matching state keys or list objects
* @param {string} list[].key - the key matching the key present in the vuex state
* @param {string} list[].getter - the name of the getter, leave it empty to not use a getter
* @param {string} list[].updateFn - the name of the action, leave it empty to use the default action
* @param {string} defaultUpdateFn - the default function to dispatch
2021-09-30 23:02:18 +05:30
* @param {string|function} root - the key of the state where to search for the keys described in list
2020-03-13 15:44:24 +05:30
* @returns {Object} a dictionary with all the computed properties generated
*/
export const mapComputed = (list, defaultUpdateFn, root) => {
const result = {};
2021-03-08 18:12:59 +05:30
list.forEach((item) => {
2020-03-13 15:44:24 +05:30
const [getter, key, updateFn] =
typeof item === 'string'
? [false, item, defaultUpdateFn]
: [item.getter, item.key, item.updateFn || defaultUpdateFn];
result[key] = {
get() {
if (getter) {
return this.$store.getters[getter];
} else if (root) {
2021-09-30 23:02:18 +05:30
if (typeof root === 'function') {
return root(this.$store.state)[key];
}
2020-03-13 15:44:24 +05:30
return this.$store.state[root][key];
}
return this.$store.state[key];
},
set(value) {
this.$store.dispatch(updateFn, { [key]: value });
},
};
});
return result;
};