解決辦法:
1.新建四個或者多個頁面(Index.vue,Classify.vue,ShoppCart.vue,My.vue)
2.新建tabbar.vue頁面
<template> <div id="tab-bar"> <slot></slot> </div> </template> <script> export default { name: 'TabBar' } </script> <style scoped> #tab-bar { display: flex; position: fixed; left: 0; right: 0; bottom: 0; background-color: #f6f6f6; box-shadow: 0 -1px 1px rgba(100, 100, 100, .1); } </style>
此處為知識鏈接:
<slot></slot>名叫插槽,在這邊主要起到的是占位的作用
3.新建tabbaritem.vue頁面
<template> <div class="tab-bar-item" @click="itemClick()"> <div v-if="!isActive"> <slot name="item-icon"></slot> </div> <div v-else> <slot name="item-icon-active"></slot> </div> <div :style="activeStyle"> <slot name="item-text"></slot> </div> </div> </template> <script> export default { name: 'TabBarItem', props: { path: String, activeColor: { type: String, default: '#1296db' } }, computed: { isActive() { return this.$route.path.indexOf(this.path) !== -1 }, activeStyle() { return this.isActive ? {color: this.activeColor} : {} } }, methods: { itemClick() { this.$router.replace(this.path).catch(() => {}) } } } </script> <style> .tab-bar-item { flex: 1; text-align: center; height: 49px; font-size: 14px; } .tab-bar-item img { display: inline-block; width: 24px; height: 24px; margin-top: 3px; vertical-align: middle; } </style>
4.在App.vue 中實現文件的引用
<template> <div id="app"> <router-view></router-view> <tab-bar> <tab-bar-item path="/home"> <img slot="item-icon" src="./assets/img/tabbar/icon_home.png" alt="首頁"> <img slot="item-icon-active" src="./assets/img/tabbar/icon_home_active.png" alt="首頁"> <div slot="item-text">首頁</div> </tab-bar-item> <tab-bar-item path="/classify"> <img slot="item-icon" src="./assets/img/tabbar/icon_classify.png" alt="分類"> <img slot="item-icon-active" src="./assets/img/tabbar/icon_classify_active.png" alt="分類"> <div slot="item-text">分類</div> </tab-bar-item> <tab-bar-item path="/shopcart"> <img slot="item-icon" src="./assets/img/tabbar/icon_shopcart.png" alt="購物車"> <img slot="item-icon-active" src="./assets/img/tabbar/icon_shopcart_active.png" alt="購物車"> <div slot="item-text">購物車</div> </tab-bar-item> <tab-bar-item path="/my"> <img slot="item-icon" src="./assets/img/tabbar/icon_my.png" alt="我的"> <img slot="item-icon-active" src="./assets/img/tabbar/icon_my_active.png" alt="我的"> <div slot="item-text">我的</div> </tab-bar-item> </tab-bar> </div> </template> <script> import TabBar from './components/tabbar/TabBar.vue' import TabBarItem from './components/tabbar/TabBarItem.vue' export default { name: 'App', components: { TabBar, TabBarItem } } </script> <style></style>
原文鏈接:Vue實現底部導航