h5项目中,常常用到的头部是样式是一致的,只是左右按钮和中间标题会不一致。html
vue主打组件化,为了减小代码冗余,能够将头部提取成一个单独的组件。接下来考虑是否须要左右按钮,是否固定在页面上不动,中间标题是否为动态。vue
先写一个简单的头部,position设置成变量customFixed。左右按钮经过<slot>来控制。中间标题设置成变量customTitle经过父子组件传值过来。app
设置好样式之后给customFixed和customTitle默认值和类型。组件化
<template> <div id="header" :style="{'position' : customFixed ? 'fixed' : 'absolute'}"> <slot name="left"></slot> {{customTitle}} <slot name="right"></slot> </div> </template> <script> export default { name: "my-header", props:{ customTitle : { type : String, default : '标题' }, customFixed: { type: Boolean, default: false } } } </script> <style scoped> #header{ width: 100%;height: 40px;background: #666;color: white;text-align: center;line-height: 40px; position: absolute;left:0;top: 0;z-index: 10; } #header button {height: 100%;padding: 0 50px;} #header button:nth-of-type(1){float: left} #header button:nth-of-type(2){float: right} </style>
在用到头部的地方:spa
<template> <div id="app"> <my-header custom-title="通信录" custom-fixed> <button @click="backBtn" slot="left">返回</button> <button @click="homeBtn" slot="right">主页</button> </my-header> </div> </template>