uniapp写小程序自定义tabbar,也更用wx写一样。
在pages.json,设置tabbar
// pages.json
// 有页面链接就好了
"tabBar": {
"color": "#000",
"selectedColor": "#303133",
"backgroundColor": "#FFFFFF",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/index/index",
"text":""
},
{
"pagePath": "pages/model/model",
"text":""
},
{
"pagePath": "pages/address/address",
"text":""
},
{
"pagePath": "pages/user/user",
"text":""
}
]
}
// tabbar.vue
<template>
<view class="tabbar">
<view class="box">
<view class="div" v-for="(item,index) in list" :key='index' @click="Jump(index)">
<image :src="require('../static/img/tabbar/'+ (ind == index ? item.positive : item.negative) + '.png')" class="img" mode="aspectFit"></image>
<text>{{item.name}}</text>
</view>
</view>
</view>
</template>
<script>
export default {
name:"tabbar",
data() {
return {
ind: 0,
list:[
{name:"首页",positive: 'tabbar1',negative: 'tabbar5',url: 'index'},
{name:"机型",positive: 'tabbar2',negative: 'tabbar6',url: 'model'},
{name:"附近设备",positive: 'tabbar3',negative: 'tabbar7',url: 'address'},
{name:"我的",positive: 'tabbar4',negative: 'tabbar8',url: 'user'}
],
};
},
onLoad() {},
computed:{},
created() {
let pages = getCurrentPages() //获取加载的页面
let currentPage = pages[pages.length - 1] //获取当前页面的对象
let url = currentPage.route //当前页面url
this.list.forEach((e, i) => {
if (e.url == url.split('/')[2]) {
// 一开始用vuex去做管理,后来发现vuex有一点点慢,就会先加载上一个状态后才接收到vuex更新,导致图标闪烁。
// this.$store.dispatch('setPage', i);
// 因为pages.json设置了tabbar,所以组件不会跟随页面重新加载,就可以直接赋值。
this.ind = i
}
})
},
methods: {
Jump(ind) {
let url = this.list[ind].url;
// 使用switchTab跳转
uni.switchTab({
url: '../../pages/' +url+ '/' +url,
})
}
},
mounted() {}
}
</script>
// app.vue
// 隐藏系统tabbar
onShow: function() {
uni.hideTabBar({
animation: false
})
},
// index.vue
// 在页面使用
<template>
<tabbar class="tabbar"></tabbar>
</template>
// index.js
// 引入组件
import tabbar from "@/components/tabbar.vue";
export default {
// 注册组组件
components: {tabbar},
}