vue项目如何进行头部组件的抽离复用

  1. 创建一个头部组件HeaderTop,对于不同的页面,头部的中间内容title可能都不一样,所以我们可以通过父子组件传值的方式,通过props进行传值。而对于头部的左边和右边的内容,有的页面可能会有,有的页面可能不会有,可以通过插槽slot去解决,slot需要指明name的值,代码如下:
<template>
    <div class="header">
        <slot name="left"></slot>
        <span class="header_title">
            <span class="header_title_text ellipsis">{{ title }}</span>
        </span>
        <slot name="right"></slot>
    </div>
</template>

<script>
export default {
  name: 'HeaderTop',
  props: {
    title: String
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
     @import '../../common/stylus/mixins.styl'
    .header
        background-color #02a774
        position fixed
        z-index 100
        left 0
        top 0
        width 100%
        height 45px
        .header_title
            position absolute
            top 50%
            left 50%
            transform translate(-50%, -50%)
            width 50%
            color #fff
            text-align center
            .header_title_text
                font-size 20px
                color #fff
                display block
</style>

  1. 创建完HeaderTop组件以后,我们就需要在页面当中去引入组件,对于头部只有中间的内容,而左边和右边没有内容的,我们就只需要去引入HeaderTop组件,然后去注册HeaderTop组件,而对于头部的内容,通过父子组件传值就可以实现,代码如下所示:
<template>
    <div class="profile">
        <HeaderTop title="个人中心"></HeaderTop>
    </div>
</template>

<script>
import HeaderTop from '../../components/HeaderTop/HeaderTop.vue'

export default {
  name: 'Profile',
  components: {
    HeaderTop
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
</style>

  1. 对于头部既有中间的内容,又有左边和右边的内容,我们就可以使用插槽。先进行引入HeaderTop组件,然后进行注册HeaderTop组件。对于头部中间的title就直接通过父子组件传值的方式,绑定属性传值。对于左边和右边的内容,使用slot,并且指明是哪一个插槽,就可以了,代码如下:
<template>
    <div class="msite">
        <HeaderTop :title="address.name">
            <router-link class="header_search" slot="left" to="/search">
                <i class="iconfont iconsousuo"></i>
            </router-link>
            <router-link class="header_login" slot="right" :to="userInfo._id ? '/userInfo' : '/login'">
                <span class="header_login_text" v-if="!userInfo._id">登录|注册</span>
                <span class="header_login_text" v-else>
                    <i class="iconfont iconwo"></i>
                </span>
            </router-link>
        </HeaderTop>
    </div>
</template>

<script>
import HeaderTop from '../../components/HeaderTop/HeaderTop.vue'

export default {
  name: 'Msite',
  components: {
    HeaderTop
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
</style>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值