Vue.js 页面组件化开发:页头、页体、页尾组件组合实现页面结构
本教程演示如何使用 Vue.js 组件化开发模式,定义页头 (Header)、页体 (Body)、页尾 (Footer) 组件,并通过组合的方式构建一个简单的网页结构。
组件定义
首先,我们定义三个组件:Header、Body 和 Footer。每个组件负责渲染页面的一部分。
1. 页头组件 Header.vue
<template>
<div class='header'>
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
}
}
};
</script>
<style scoped>
.header {
background-color: #f7f7f7;
padding: 20px;
text-align: center;
}
</style>
2. 页体组件 Body.vue
<template>
<div class='body'>
<slot></slot>
</div>
</template>
<style scoped>
.body {
padding: 20px;
}
</style>
3. 页尾组件 Footer.vue
<template>
<div class='footer'>
<p>{{ text }}</p>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true
}
}
};
</script>
<style scoped>
.footer {
background-color: #f7f7f7;
padding: 20px;
text-align: center;
}
</style>
组合页面
接下来,我们在 App.vue 中组合这些组件,构建完整的页面结构。
1. App.vue
<template>
<div class='app'>
<Header title='My Website' />
<Body>
<h2>Welcome to my website</h2>
<p>This is the main content of the page.</p>
</Body>
<Footer text='© 2021 My Website. All rights reserved.' />
</div>
</template>
<script>
import Header from './components/Header.vue';
import Body from './components/Body.vue';
import Footer from './components/Footer.vue';
export default {
components: {
Header,
Body,
Footer
}
};
</script>
<style>
.app {
max-width: 600px;
margin: 0 auto;
}
</style>
2. main.js
import Vue from 'vue';
import App from './App.vue';
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount('#app');
页面效果
My Website
Welcome to my website
This is the main content of the page.
© 2021 My Website. All rights reserved.
通过这种组件化开发模式,我们可以将页面拆分成独立的组件,每个组件负责渲染特定的部分,提高代码的可读性、可维护性和复用性。
原文地址: http://www.cveoy.top/t/topic/n3o7 著作权归作者所有。请勿转载和采集!