vant移动端 Vue 组件库的使用之Tabbar 标签栏
2019-03-11 本文已影响90人
程序猿阿峰
image.png
可以轻松解决这个问题
vant 是轻量、可靠的移动端 Vue 组件库
特性
- 50+ 个经过有赞线上业务检验的组件
- 80%+ 单元测试覆盖率
- 完善的文档和示例
- 支持 babel-plugin-import
- 支持 TypeScript
- 支持 SSR
快速上手
脚手架
推荐使用 Vue 官方提供的脚手架 Vue Cli 3 创建项目
# 安装 Vue Cli
npm install -g @vue/cli
# 创建一个项目
vue create hello-world
安装
NPM
npm i vant -S
YARN
yarn add vant
CDN
<!-- 引入样式 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@1.6/lib/index.css">
<!-- 引入组件 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vant@1.6/lib/vant.min.js"></script>
按需引入组件
在不使用插件的情况下,可以手动引入需要的组件
import Button from 'vant/lib/button';
import 'vant/lib/button/style';
NavBar 导航栏 的使用
import { Tabbar, TabbarItem } from 'vant';
Vue.use(Tabbar).use(TabbarItem);
项目中使用
tab-bar组件
<template>
<div class="tab-bar">
<van-tabbar v-model="active" @change="change">
<van-tabbar-item to="/Home" replace>
<span>门店</span>
<img
slot="icon"
slot-scope="props"
:src="props.active ? icon.active : icon.normal"
>
</van-tabbar-item>
<van-tabbar-item to="/NewPersonal" replace>
<span>我的</span>
<img
slot="icon"
slot-scope="props"
:src="props.active ? icon.myactive : icon.mynormal"
>
</van-tabbar-item>
</van-tabbar>
</div>
</template>
<script>
export default {
props: {
courrentTabBar: {
type: String
}
},
data () {
return {
active: '',
icon: {
normal: './static/image/normal.png',
active: './static/image/active.png',
gnnormal: './static/image/manager-normal.png',
gnactive: './static/image/manage-active.png',
mynormal: './static/image/my-normal.png',
myactive: './static/image/my-active.png'
}
}
},
methods: {
/**
* tab栏的切换
*/
change () {
if (this.active === 0) {
this.$router.push({
path: '/Home',
replace: true
})
} else if (this.active === 1) {
this.$router.push({
path: '/Personal',
replace: true
})
}
}
},
mounted () {
// 判断当前页面是否为home或newpersonal页面
const CURRENTTABBAR = window.location.hash.split('/')[1]
if (CURRENTTABBAR === 'Home') {
this.active = 0
} else if (CURRENTTABBAR === 'NewPersonal') {
this.active = 1
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.tab-bar{
height: 44px;
}
</style>
main 组件
<template>
<div class="main">
<router-view></router-view>
<my-tabbar />
</div>
</template>
<script>
import TabBar from '@/components/tabbar.vue'
export default {
name: 'main',
components: {
'my-tabbar': TabBar
}
}
</script>
<style lang="scss" scoped>
.main{
height: 100%;
}
</style>
问题
假如从首页进入某一页面,点击返回首页,Tabbar标签栏不会被选中?
解决
image.png在首页上添加mounted
钩子函数,动态获取地址栏上的hash
值来判断当前时哪个页面。
可以轻松解决这个问题
记录于 2019-3-11 18:59