Skip to content

Instantly share code, notes, and snippets.

@innocenzi
Created October 17, 2019 17:44
Show Gist options
  • Save innocenzi/c42b70262499da34e381c2bdebed73f9 to your computer and use it in GitHub Desktop.
Save innocenzi/c42b70262499da34e381c2bdebed73f9 to your computer and use it in GitHub Desktop.
Inertia + Vue dynamic layout
<template>
<component :is="layout"><slot /></component>
</template>
<script>
import Drawer from '@/Layout/Drawer';
import Fullscreen from '@/Layout/Fullscreen';
import v from 'voca';
const fallback = 'drawer';
const layouts = {
Drawer,
Fullscreen
}
// This export is made to be able to have a certain layout
// defined in a file.
// Import with `import { Layout } from '@/Layout/Layout'`
// Then use `layout: Layout('layout-name')`.
export const Layout = (type) => {
const Layout = require('./Layout').default;
Layout.computed.type = () => type;
return Layout;
}
export default {
components: layouts,
computed: {
layout() {
return this.parseLayout(this.$page.layout) || this.parseLayout(this.type) || fallback;
}
},
methods: {
parseLayout(name) {
name = v.kebabCase(name);
if (name) {
if (Object.keys(layouts).map(name => v.kebabCase(name)).includes(name)) {
return name;
}
console.warn(`Unknown layout '${name}', defaulting to '${fallback}'.`);
return fallback;
}
return null;
}
}
}
</script>
<script>
import { Layout } from "@/Layout/Layout";
export default {
layout: Layout('drawer'),
props: {
errors: Object
},
// ...
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment