Skip to content

Instantly share code, notes, and snippets.

@mavyfaby
Created January 9, 2022 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mavyfaby/7d05e5542f5d10c77c25da42a44822df to your computer and use it in GitHub Desktop.
Save mavyfaby/7d05e5542f5d10c77c25da42a44822df to your computer and use it in GitHub Desktop.
Vuex 4 and Vue 3: Create models from vuex state
import { computed } from "vue";
/**
* Create models from state
* @param {object} vuex state
* @returns {(object | null)} state models
*/
function createModels(state) {
// Check if state is not empty and a valid object
if (state && typeof state === "object" && state.constructor === Object) {
// Get keys
const keys = Object.keys(state);
// Computed states
const models = {};
// For every keys
for (const key of keys) {
// Create a computed property
models[key] = computed({
get: () => state[key],
set: (val) => state[key] = val
});
}
// Return models
return models;
}
// Otherwise, return null
return null;
}
export {
createModels
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment