Vue封装Tabbar组件
话不多说直接上代码
在App.vue 封装 路由跳转 利用router-view的特性
<template>
<div id="app">
<router-view />
//引入子组件 把items 这个数组传进去
<Tabr :items="items" />
</div>
</template>
<script>
import Tabr from "./components/Tabr";
export default {
components: {
Tabr,
},
data() {
return {
items: [
{
title: "首页",
path: "/",
img: require("./assets/img/shouye.png"),
imgs: require("./assets/img/shouye_1.png"),
},
{
title: "分类",
path: "/About",
img: require("./assets/img/fenlei.png"),
imgs: require("./assets/img/fenlei_1.png"),
},
{
title: "购物车",
path: "/Cart",
img: require("./assets/img/gouwuchezhengpin.png"),
imgs: require("./assets/img/gouwuchezhengpin_1.png"),
},
{
title: "我的",
path: "/Mime",
img: require("./assets/img/wode.png"),
imgs: require("./assets/img/wode_1.png"),
},
],
};
},
};
</script>
子组件Tabbar
<template>
<div class="Yanxuan_tab">
<div v-for="(item,index) in items" :key="index" @click="Onclick(index)">
<div>
<img :src="index===Tabindex?item.imgs:item.img" alt />
//动态绑定
</div>
<div :class="index===Tabindex?'title':'Yanxuan_title'">
//
{{item.title}}</div>
</div>
</div>
</template>
<script>
export default {
props: {
items: {
type: Array,
required: true,
validator: function (value) {
return value.length <= 6;
//市面常见的Tabbar的栏 不能超过6个
},
}
},
data() {
return {
item:this.items,
Tabindex:0
}
},
methods:{
Onclick(index){
//这里是根据下标切换 图片样式跟字体颜色 动态绑定
this.Tabindex = index
var temp = this.item[index]
this.$router.push(temp.path)
}
}
};
</script>
<style scoped>
.Yanxuan_tab {
width: 100%;
height: 64px;
border: 1px solid gainsboro;
position: fixed;
bottom: 0px;
left: 0px;
display: inline-flex;
justify-content: space-around;
align-items: center;
text-align: center;
}
.Yanxuan_title{
font-size: 14px;
}
.title{
font-size: 14px;
color:red
}
</style>
然后就是配置的路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta:{
isShowTabbar:true
}
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
meta:{
isShowTabbar:true
}
}
,
{
path: '/Cart',
name: 'Cart',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/Cart.vue'),
meta:{
isShowTabbar:false
}
},
{
path: '/Mime',
name: 'Mime',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/Mime.vue'),
meta:{
isShowTabbar:true
}
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
最后的效果完成图
代码就直接可以用了