在uniapp 中,按照easycom规范创建的组件可以直接在uniapp中使用,无需引用和注册组件。
下面来封装一个uniapp自定义顶部导航的组件,组件命名为myNav
。
创建组件要符合 components/组件名称/组件名称.vue
的目录结构。如下:
- node_modules
- static
- pages
- unpackage
- components
- myNav
- myNav.vue
myNav组件文件目录结构为components/myNav/myNav.vue
myNav组件 的完整代码
<template>
<view class="nav-ful">
<view :class="['my-nav' ,{'fixed':fixeddir}]">
<view class="status_bar"></view>
<view class="d-flex a-center">
<view class="nav-arrow-left" v-if="arrowleft" @click="historyBack"><u-icon name="arrow-left" color="#fff" size="36rpx"></u-icon></view>
<text class="my-nav-title">{{$props.title}}</text>
</view>
</view>
</view>
</template>
<script>
export default {
name:"myNav",
props:['title','arrow','fixed'],
data() {
return {
arrowleft:false,
fixeddir:true
};
},
created(){
this.arrowleft = this.$props.arrow || false
this.fixeddir = this.$props.fixed || true
},
methods:{
historyBack(){
uni.navigateBack({
delta:1
})
}
}
}
</script>
<style lang="scss" scoped>
$h:80rpx;
.nav-ful {
padding-bottom: calc(var(--status-bar-height) + #{$h});
}
.my-nav {
background:linear-gradient(to right ,#0F5FDC ,#26A3FF);
.my-nav-title {
color: #fff;
font-size: 36rpx;
height: $h;
line-height: $h;
flex:1;
text-overflow:ellipsis;
white-space: nowrap;
overflow: hidden;
text-align: center;
padding: 0 15rpx;
// background-color: #999;
}
.nav-arrow-left {
width: 80rpx;
display: flex;
align-items: center;
justify-content: center;
}
.nav-arrow-left+.my-nav-title {
margin-left: -80rpx;
padding: 0 80rpx;
}
// #ifdef H5
height: auto;
// #endif
}
.fixed {
position: fixed;
top: 0;
left: 0;
width: 750rpx;
z-index: 99;
}
</style>
App状态栏高度var(--status-bar-height)
+ 导航的高度#{$h} 就是自定义顶部导航的高度。
$h:100rpx;
calc(var(--status-bar-height) + #{$h});
myNav组件遵循easycom规范。无需引入和注册,直接使用。
<template>
<view class="container">
<myNav title="首页" :arrow="true"></myNav>
</view>
</template>