...

/

Products Layout

Products Layout

Learn how to manage the products layout with the useLayoutFactory composable.

Products layout using useLayoutFactory

Let’s create one more layout, but this time for products. Allowing users to choose how they want to view products on our website is a good idea. A website could then allow users to switch between different layouts for products, like grid and list. We’ll create this functionality using the useLayoutFactory composable we created before. The figures below (Product grid layout and Product list layout) show what the final layouts should look like.

We need another route and a set of components for this example. First, let’s create a new layout component called ProductLayout.vue. The template is exactly the same as in the Layout.vue component, and the script part differs only slightly. Why would we have almost exactly the same component? Don’t worry about this, we’ll avoid this repetition soon.

<!-- layout/ProductLayout.vue -->
<template>
<component :is="currentLayoutComponent">
<template
v-for="slotName in Object.keys($slots)"
:key="slotName"
v-slot:[slotName]="slotProps"
>
<slot :name="slotName" :layout="layout" v-bind="slotProps" />
</template>
</component>
</template>
Creating the template for products layout

Notice that we import files that don’t exist yet. We’ll create them in a moment. First, let’s take care of the GridLayout and ListLayout components. The former has a bit of styling to display a grid layout, while the latter only forces minimum height on child elements.

<!-- layout/components/GridLayout.vue -->
<template>
<div :class="$style.gridLayout">
<slot />
</div>
</template>
<script>
export default {}
</script>
<style module>
.gridLayout {
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
@apply gap-8 grid;
}
</style>
Implementation of the grid layout component

Now, let’s create the useProductLayout.js file :

Press + to interact
// layout/composables/useProductLayout.js
import { useLayoutFactory } from "../helpers/useLayoutFactory";
export const LAYOUTS = {
grid: Symbol("grid"),
list: Symbol("list"),
};
const { useLayout: useProductLayout } = useLayoutFactory(LAYOUTS, LAYOUTS.grid);
export { useProductLayout };

Here, we make use of the useLayoutFactory function created earlier. We have the ...