Dynamic Layout with a pageLayoutService

Learn how to manage dynamic layouts using layout service and use it in our projects.

In the previous example, we derived information from the route meta object to display the appropriate layout component. This time, we won’t rely on the layout/standard and layout/auth paths defined in the router.js file. Instead, we’ll have a reactive state in a service file. Because it’s directly related to the layout functionality, we won’t put it in the global services folder, but instead in the layout directory, so the file path will be src/layout/services/pageLayoutService.js.

Usable layout service

For a usable layout service, we need to be able to:

  1. Reactively store the currently selected layout so that all consumers can re-render and show the appropriate layout component.

  2. Allow components to consume the currently selected layout type.

  3. Provide a way to update the layout type.

We can accomplish the first step by using the reactive method. We can use the observable method instead of reactive if we’re developing in Vue 2. The observable method was added in Vue 2.6. For the second step, we can provide an object to be used as a computed property. Last but not least, the layout can be updated by using a setLayout function or a computed setter. Here’s the code:

Get hands-on with 1200+ tech skills courses.