Vue + Vant 实现页面顶端 TopBar

我们在做移动端开发时,有的页面顶部需要设置标题、返回上一页面箭头、关闭按钮等。不同的页面的标题不同,有的页面需要返回按钮、有的页面需要关闭按钮。我们可以根据需求,将其封装成 TopBar 组件,标题运用 Vue 组件的 props 实现动态赋值,供其他组件引用。

 

效果图:

 

TopBar.vue:

1.<template></template>

<template>
  <div class="top-bar" :class="[ (!hasBack && !hasClose) ? 'center' : 'between' ]">
    <van-icon v-if="hasBack" class="back-icon" name="arrow-left" @click="goBack" />
    <van-icon v-if="hasClose" class="back-icon" name="arrow-left" />
    <span>{{title}}</span>
    <div></div>
  </div>
</template>

注意:倒数第三行的 <div></div> 非常重要! 这为下一步,为 .tob-bar 的 {{ title }} 设置 flex 布局的 justify-conent:center 实现居中显示。如果不加,若有左侧返回箭头时,将 title 居中实现起来很麻烦。

 

2.<script></script>

props: {
  title: { type: String, default: '' },
  hasBack: { type: Boolean, default: false },
  hasClose: { type: Boolean, default: false },
},

其中 title 接受不同页面的标题。

 

3.<style></style>

<style lang="scss" scoped>
  .top-bar {
    display: flex;
    align-items: center;
    height: 11.5vw;
    padding: 0 3vw;
    background: #fff;
    border-bottom: 1px solid #eee;
    font-size: 4.5vw;
    box-sizing: border-box;
  }
  .center {
    justify-content: center;
  }
  .between {
    justify-content: space-between;
  }
</style>

 

4. 父组件引用:

组件局部注册:

<script>
  import TopBar from '@/components/TopBar';
  
  export default {
    components: {
      TopBar,
    },
  }
</script>

 

引用:

<template>
  <div class="city-container">
    <top-bar title="城市列表" hasBack></top-bar>
  </div>
</template>

title 向 props 中传入静态值, hasBack 无值,则默认为 true.

 

就到这里啦。很简单吧 🙂,一起加油哦!

 

posted @ 2020-07-16 11:28  几行  阅读(4197)  评论(0编辑  收藏  举报