uni-app微信小程序全局配置自定义导航栏有哪些方法?
作者:互联网
可以通过以下几种方式实现。为了确保所有页面都使用统一的自定义导航栏样式和功能,建议使用组件化的方式,并结合 pages.json
和条件编译进行适配。
方法一:创建全局自定义导航栏组件
-
创建自定义导航栏组件: 创建一个新的组件(如
CustomNav.vue
),并在其中编写自定义的 HTML 和样式。<!-- components/CustomNav.vue --> <template> <view class="custom-nav"> <view class="nav-left" @click="goBack">返回</view> <view class="nav-title">{{ title }}</view> <view class="nav-right">更多</view> </view> </template> <script> export default { name: 'CustomNav', props: { title: { type: String, default: '标题' } }, methods: { goBack() { uni.navigateBack(); } } }; </script> <style scoped> .custom-nav { display: flex; justify-content: space-between; align-items: center; padding: 0 20px; height: 44px; background-color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); } .nav-left, .nav-right { font-size: 16px; } .nav-title { flex-grow: 1; text-align: center; font-size: 18px; font-weight: bold; } </style>
Vue -
启用自定义导航栏: 在
pages.json
中将所有页面的navigationStyle
设置为custom
。{ "globalStyle": { "navigationStyle": "custom" }, "pages": [ { "path": "pages/index/index", "style": { "navigationStyle": "custom" } }, { "path": "pages/about/about", "style": { "navigationStyle": "custom" } } // 其他页面... ] }
JSON -
在页面中使用自定义导航栏组件: 在每个页面的模板中引入并使用
CustomNav
组件,并传递页面标题作为 prop。<!-- pages/index/index.vue --> <template> <view> <CustomNav :title="'首页'" /> <view class="page-content"> <!-- 页面内容 --> </view> </view> </template> <script> import CustomNav from '@/components/CustomNav.vue'; export default { components: { CustomNav } }; </script> <style> .page-content { padding-top: 44px; /* 确保内容不被导航栏遮挡 */ } </style>
Vue
方法二:使用 Mixin 或全局注册组件
为了进一步简化代码,可以使用 Vue 的 Mixin 或全局注册组件来自动引入自定义导航栏。
-
创建 Mixin: 创建一个 Mixin 文件(如
customNavMixin.js
),用于自动引入CustomNav
组件。// mixins/customNavMixin.js import CustomNav from '@/components/CustomNav.vue'; export default { data() { return { navTitle: '' }; }, created() { this.navTitle = this.$mp.page.route.split('/').pop().replace(/\.vue$/, ''); }, components: { CustomNav } };
JavaScript -
在页面中使用 Mixin: 在每个页面中使用该 Mixin,并传递页面标题。
<!-- pages/index/index.vue --> <template> <view> <CustomNav :title="navTitle" /> <view class="page-content"> <!-- 页面内容 --> </view> </view> </template> <script> import customNavMixin from '@/mixins/customNavMixin'; export default { mixins: [customNavMixin] }; </script> <style> .page-content { padding-top: 44px; /* 确保内容不被导航栏遮挡 */ } </style>
Vue -
全局注册组件: 你还可以在
main.js
中全局注册CustomNav
组件,这样就不需要在每个页面中手动引入。// main.js import Vue from 'vue'; import App from './App'; import CustomNav from '@/components/CustomNav.vue'; Vue.component('CustomNav', CustomNav); Vue.config.productionTip = false; App.mpType = 'app'; const app = new Vue({ ...App
JavaScript
}); app.$mount();
### 方法三:使用条件编译和平台适配
由于不同平台(如微信小程序、H5、App 等)的默认导航栏高度可能不同,建议使用条件编译来进行适配。
```css
/* 在 App.vue 的 <style> 标签中 */
/* #ifdef MP-WEIXIN */
page {
padding-top: 44px; /* 微信小程序的导航栏高度 */
}
/* #endif */
/* #ifdef H5 */
page {
padding-top: 0; /* H5 平台不需要额外间距 */
}
/* #endif */
标签: 来源: