Layout Component
Components are reusable independent pieces of your application UI. The layout component is a component used to share a common section across multiple pages. The layout component mostly will have the common header, sidebar, and footer section.
-
- Create App
-
- Folder structure
-
- Create Header Component
-
- Create Footer component
-
- Create Layout component
-
- Add Layout to the Root component
1. Create App
Create your Vite-powered Vue project using the create-vue
npm init vue@latest✔ Project name: … <your-project-name>
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add Cypress for both Unit and End-to-End testing? … No / Yes
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes
Scaffolding project in ./<your-project-name>...
Done.
If you are unsure about an option, simply choose No
by hitting enter for now. Once the project is created, follow the instructions to install dependencies and start the dev server:
> cd <your-project-name>
> npm install
> npm run dev
2. Folder structure
Create the Layout folder inside the components folder. Also, create the Header and Footer components.
3. Create Header Component
Create your header and footer components using the below code:
src/components/Layout/Header/Header.vue
<template>
<h1>Header</h1>
</template><script>
export default {
name: 'Header'
}
</script>
4. Create Footer component
src/components/Layout/Footer/Footer.vue
<template>
<h1>Footer</h1>
</template>
<script>
export default {
name: 'Footer'
}
</script>
5. Create Layout component
Now we going to create our Layout
component. Import the Header and Footer components into the Layout component. The<slot>
is used to display the content of the component.
src/components/Layout/Layout.vue
<template>
<Header />
<slot />
<Footer />
</template>
<script>
import Header from './Header/Header.vue'
import Footer from './Footer/Footer.vue'
export default {
name: 'Layout',
components: {
Header,
Footer
}
}
</script>
6. Add Layout to the Root component
The App component is a root component of our application. Add the layout to the root component.
src/App.vue
<template>
<div id="app">
<Layout>
<img alt="Vue logo" src="https://vuejs.org/images/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</Layout>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import Layout from './components/Layout/Layout.vue'
export default {
name: 'App',
components: {
Layout,
HelloWorld
}
}
</script>
Output
This example code is available at https://github.com/balajidharma/vue-basic-layout
StackBlitz application
We successfully created our own layout component. This is a basic Vue.js layout component, hope it will help you to understand the basic layout flow.
Thank you for reading.