创建组件
创建一个名为Top.vue的头部组件
在组件内,我们设置要共享的样式,如果所对应的头部内容不一样,则使用props
<template>
<div>
<div class="top">
<div class="zi">{{ headerText }}</div>
</div>
</div>
</template>
<script>
export default {
props: {
headerText: {
type: String,
required: true
}
}
}
</script>
<style lang="scss" scoped>
*{
margin: 0;
padding: 0;
}
body,html,#root{
margin: 0;
padding: 0;
}
.top{
width: 100%;
height: 50px;
background-color: rgb(144, 82, 237);
color: white;
font-size: 26px;
padding-top: 15px;
box-sizing: border-box;
padding-left: 10px;
display: flex;
z-index: 999;
.zi{
font-size: 18px;
margin: 0 auto;
width: 100%;
position: fixed;
text-align: center;
}
}
</style>
在上面的示例中,我们定义了一个headerText属性作为头部组件的传入值。在模板中,我们使用双花括号插值语法{{ title }}
来显示传入的标题。注意,我们还为头部组件添加了样式,以设置背景颜色和内边距。
引入组件
<template>
<Top :headerText="'pageTitle'" />
</template>
<script>
import Top from '../Top.vue';
export default {
components: {
Top
}
};
</script>
我们引入了头部组件Top
,并将pageTitle
作为headerText属性的值传递给头部组件。通过使用:
绑定语法,我们可以将pageTitle
变量的值传递给子组件。
这样,头部组件就可以在其模板中显示传入的标题了。你可以根据实际需求在父组件中动态修改pageTitle
的值,并观察头部组件是否正确地更新显示。