Vue

vue + router + vant + navbar组件封

2019-10-23  本文已影响0人  艳晓

本项目选择vuecli3+vant进行移动端页面开发。
本文是针对导航栏进行的简单封装

1、在main.js中导入NavBar

import { NavBar } from 'vant';
Vue.use(NavBar);

2、创建NavBar组件用来封装vant提供的<van-nav-bar>

2.1设置数据绑定的title,左侧返回箭头是否显示
<template>
  <div id="NavBar">
    <van-nav-bar :title="title" :left-arrow="isleftarrow" @click-left="onClickLeft" />
  </div>
</template>
2.2 使用props由父组件给子组件传值,父组件动态给导航栏赋值。
<script>
export default {
  // title:用来显示导航栏的title,isleftarrow用来显示导航栏的左侧返回箭头
  props: ["title","isleftarrow"],
  methods: {
    onClickLeft() {
      // 点击回退的时候当做地址回退
      this.$router.go(-1);
    }
  }
};
</script>
<style scoped>
#NavBar {
  position: fixed;
  top: 0;
  left: 0;
  height: 46px;
  line-height: 46px;
  width:100%;
  z-index: 100;
}
.van-nav-bar{
  font-size: 18px!important;
  /* 设置导航栏的渐变色 */
  background: linear-gradient(to right, #ff2e29, #fe6e49)!important;
  background: -webkit-linear-gradient(to right, #ff2e29, #fe6e49)!important;
  border:0;
}
.van-hairline--bottom::after {
     /* 去除导航栏底部的白色横线 */
    border-bottom-width: 0px!important;
}

</style>

3、在父组件中使用该导航栏作为公共部分并赋值

  <div id="app">
    <NavBar v-show="navShow" :title="title" :isleftarrow="isleftarrow">      </NavBar>
3.1引用导航栏组件
import NavBar from "./components/Common/NavBar.vue";
export default {
  components: {
    NavBar
  },
3.2设置属性值与导航栏组件进行数据绑定(title:'', isleftarrow:'')
  data() {
    return {
      title:'',
      isleftarrow:'',
      transitionName: "fade",
      navShow: true
    };
  },
3.3在mounted中给 title和isleftarrow赋值

:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。

  mounted() {
    this.title = this.$route.meta.title;
    this.isleftarrow = this.$route.meta.isleftarrow;       
  },
3.4使用watch检测路由切换给 title和isleftarrow赋值。
  watch: {
    $route(to, from) {
      this.title = to.meta.title;
      this.isleftarrow =  to.meta.isleftarrow;
     }
  }

4、在router.js中设置meta(在3.3和3.4的取值使用)

routes: [
{
  path: '/apply',
  name: 'apply',
  meta: { title: '导航标题1', isleftarrow:true  },
  component: Apply
},
{
  path: '/',
  name: 'exhibition',
  meta: { title: '导航标题2', isleftarrow:false },
  component: Exhibition
}
]
上一篇 下一篇

猜你喜欢

热点阅读