...

/

Dynamic Layout with a useLayout Composable

Dynamic Layout with a useLayout Composable

Learn how to manage dynamic layouts using uselayout composable.

Manage layout using Composition API

Composition API is another way in which we can manage layouts. We’ll create a useLayout composable that works in a similar way to the pageLayoutService, but the code will be much more succinct, as we’ll see in a moment. Due to how the Composition API works, we won’t need the layoutComputed. Instead, we only need to define a reactive value with the ref and provide the useLayout function.

Press + to interact
// layout/composables/useLayout.js
import { ref } from "vue";
export const LAYOUTS = {
standard: Symbol("standard"),
auth: Symbol("auth"),
};
const layout = ref(LAYOUTS.standard);
const setLayout = layoutType => {
layout.value = layoutType;
};
export const useLayout = () => {
return {
layout,
setLayout,
LAYOUTS,
};
};

As in the previous example, we also have to update the Layout and LayoutExample components.

In the LayoutExample component, we update the script like this:

Press + to interact
// views/LayoutExample.vue
<script>
import Layout from "@/layout/Layout";
import { useLayout } from "@/layout/composables/useLayout";
export default {
components: {
Layout,
},
setup() {
const { setLayout, LAYOUTS } = useLayout();
return {
setLayout,
LAYOUTS,
};
},
};
</script>

The updated script for the Layout component is:

Press + to interact
// layout/Layout.vue
<script>
import { computed } from "vue";
import StandardLayout from "./components/StandardLayout";
import AuthLayout from "./components/AuthLayout";
import { useLayout } from "./composables/useLayout";
export default {
setup() {
const { layout, LAYOUTS } = useLayout();
const layoutComponents = {
[LAYOUTS.standard]: StandardLayout,
[LAYOUTS.auth]: AuthLayout,
};
const currentLayoutComponent = computed(
() => layoutComponents[layout.value]
);
return {
currentLayoutComponent,
};
},
};
</script>

As mentioned before, the useLayout.js requires less code than the layoutService, and consuming its values and methods is much cleaner, as we don’t have to spread layoutComputed, nor assign LAYOUTS on the instance in the created hook. We initialize ...