Skip to content

Instantly share code, notes, and snippets.

@gelbehexe
Last active February 8, 2021 15:29
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 gelbehexe/d1ffd65f262359582d23e08c183c2875 to your computer and use it in GitHub Desktop.
Save gelbehexe/d1ffd65f262359582d23e08c183c2875 to your computer and use it in GitHub Desktop.
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 { createStore } from "vuex"
const store = createStore({
state() {
return {
configuration: {},
}
},
mutations: {
setConfiguration(state, payload) {
state.configuration = payload
},
},
})
export default store
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