Last active
February 8, 2021 15:29
-
-
Save gelbehexe/d1ffd65f262359582d23e08c183c2875 to your computer and use it in GitHub Desktop.
config function for usage in vue/vuex 3 (like in laravel)
This file contains 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
<template> | |
<div> | |
<h1>{{ pageTitle }}</h1> | |
</div> | |
</template> | |
<script> | |
import useConfig from "../composition/useConfig" | |
// vue 2 | |
export default { | |
name: "ExampleComponent", | |
data() { | |
const { config } = useConfig() | |
const pageTitle = config("config.page.title", "Default Page Title") | |
return { | |
pageTitle, | |
} | |
}, | |
} | |
// vue 3 | |
export default { | |
name: "ExampleComponent", | |
setup() { | |
const config = useConfig() | |
const pageTitle = config("config.page.title", "Default Page Title") | |
return { | |
pageTitle, | |
} | |
}, | |
} | |
</script> | |
<style scoped> | |
</style> |
This file contains 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 { createStore } from "vuex" | |
const store = createStore({ | |
state() { | |
return { | |
configuration: {}, | |
} | |
}, | |
mutations: { | |
setConfiguration(state, payload) { | |
state.configuration = payload | |
}, | |
}, | |
}) | |
export default store | |
This file contains 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 { useStore } from "vuex" | |
/** | |
* | |
* @returns {{config: (function(String, *=): *)}} | |
*/ | |
export default function useConfig() { | |
const store = useStore() | |
const configArray = store.state.configuration | |
/** | |
* | |
* @param {String} key | |
* @param {*} defaultValue | |
* @returns {*} | |
*/ | |
function config(key, defaultValue = null) { | |
if (!key) { | |
return defaultValue | |
} | |
const keyPaths = String(key).split(".") | |
let { result } = { ...{ result: defaultValue } } | |
let next = configArray | |
while (keyPaths.length) { | |
const current = keyPaths.shift() | |
if ( | |
typeof next !== "object" || | |
next[current] === undefined | |
) { | |
return defaultValue | |
} else { | |
const { nextResult } = { ...{ nextResult: next[current] } } | |
result = nextResult | |
next = nextResult | |
} | |
} | |
return result | |
} | |
return { | |
config, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment