Vue组件的抽离和封装

1.背景

	日常开发中,有时候有些组件是功能类似甚至完全相同的情况,这个时候我们完全没必要再重新写一个,
可以抽离复用可以减少大量的时间,案例:

Vue组件的抽离和封装_第1张图片

	像一些App底部的标签页,在进行一些标签的跳转时,底部的只是变化选中时的字体颜色和图标,
大部分的元素都相同。

2.抽离思路

2.1先抽出一个大的可以装里面小组件的大容器TabBar
<div class='tabBar'>
   <tab-bar-item v-for="(val,index) in navBar" :path='val.path' fontColor='#009E97'>
       <template v-slot:icon-active>
           <img :src="val.activeImg">
       </template>
       <template v-slot:icon-inactive>
           <img :src="val.inactiveImg">
       </template>
       <template v-slot:text>
           {{val.name}}
       </template>
   </tab-bar-item>
  
 </div>
2.2实现里面各个小组件,这里要用具名插槽
<div class='tabBarItem' @click="itemHandle">
   <div v-if="iconActive">
     <slot name="icon-active"></slot>
   </div>
   <div v-else="!iconActive">
     <slot name="icon-inactive"></slot>
   </div>
   <div :style="changeColor" class="text">
     <slot name="text"></slot>
   </div>
 </div>
 因为底部的标签页跳转是要更换图标,因此可以用v-if,v-else来控制显示。
2.3要使得这类组件具有通用性和复用性,有些数据是不能写死的。
								tabBarItem.vue
props: {
   path: String,
   fontColor: {
     type: String,
     default: "#A3A3A3",
   },
 },
	我们可以在tabBar通过传递path,fontColor来改变里面子组件相关的属性,更多的属性可以
视情况而定
2.4根据路由跳转来对比父组件传进来的路径,可以得出哪个标签点击。
 computed: {
    //根据路由判断图标的激活状态
    iconActive() {
      return this.$route.path === this.path;
    },
    changeColor() {
      //标签页点击了则进行 判断,改变对应点击的字体颜色
      if (this.$route.path === this.path) {
        return { color: "#009E97" };
      } else {
        return { color: "#A3A3A3" };
      }
    },
  },
  methods: {
    itemHandle() {
      this.$router.push(this.path);
    },
  },

3.优点

1.节省时间,减少代码
2,组件利用率高,适用性广
3.减少代码的堆积,代码模块化,便于维护和修改

你可能感兴趣的:(笔记,vue,html,javascript,js)