config function for usage in vue/vuex 3 (like in laravel)
<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> |
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