Created
January 9, 2022 09:48
-
-
Save mavyfaby/7d05e5542f5d10c77c25da42a44822df to your computer and use it in GitHub Desktop.
Vuex 4 and Vue 3: Create models from vuex state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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